Pandas: summarize multiple columns into one column

If I have a data frame like this

Apples Bananas Grapes Kiwis 2 3 nan 1 1 3 7 nan nan nan 2 3 

I would like to add a column like this

 Apples Bananas Grapes Kiwis Fruit Total 2 3 nan 1 6 1 3 7 nan 11 nan nan 2 3 5 

I think you could use df['Apples'] + df['Bananas'] etc., but my actual framework is much larger than that. I was hoping that a formula like df['Fruit Total']=df[-4:-1].sum could do the trick in one line of code. However, this did not work. Is there a way to do this without explicitly summing all the columns?

+6
source share
1 answer

You can select iloc first and then sum :

 df['Fruit Total']= df.iloc[:, -4:-1].sum(axis=1) print (df) Apples Bananas Grapes Kiwis Fruit Total 0 2.0 3.0 NaN 1.0 5.0 1 1.0 3.0 7.0 NaN 11.0 2 NaN NaN 2.0 3.0 2.0 
+6
source

Source: https://habr.com/ru/post/1014723/


All Articles