0

This is my first time posting :)

In a Python data frame, how could I get the total for just certain columns? For example in the data frame below, the total for column "c_2" and column "c_3"

           X           c_1       c_2             c_3   
0          A           84        10.0           70.0   
1          B           76         70.0          125.0   
2          C           25         79.0           16.0   
3          D           28         28.0           31.0   
4          E           15         20.0           15.0   
5          F           80        195.0           10.0  

I've used df['c_2'].sum() to get the total for one column at a time, but is there a way to get the total of several, specific columns at a time? In this example the total for c_2 and total for c_3 separately.
I've seen examples for getting the total for all columns, but not examples for just certain columns.

Thank you!

laura
  • 1
  • 2
  • 1
    Not sure if this is what you are after : ``df.filter(like="_").sum()`` or you could pass a list of the interested columns to `loc` and then sum : ``df.loc[:, ["c_1", "c_2"]].sum()`` – sammywemmy Dec 22 '20 at 12:01
  • Just provide the list of all columns. ```df[["c_1","c_2"]].sum()``` – Hamza usman ghani Dec 22 '20 at 12:04
  • Thank you, @Hamzausmanghani! Your solution work. I tried a similar code, but forgot to put the double bracket. That extra bracket made the whole difference. Now, how do I make the accepted answer? – laura Dec 22 '20 at 15:26
  • @Sammywemmy I also tried your solution and it worked too. Thank you! I liked how you used the `like='_'`, I can use it as a filter to add up columns that share part of the name. – laura Dec 22 '20 at 15:31

0 Answers0