pandas :将多列汇总为一列而没有最后一列 [英] Pandas: sum up multiple columns into one column without last column

查看:63
本文介绍了 pandas :将多列汇总为一列而没有最后一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有与此类似的数据框

If I have a dataframe similar to this one

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

我想添加一个这样的列

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

我猜您可以使用df['Apples'] + df['Bananas']等,但是我的实际数据帧比这大得多.我希望像df['Fruit Total']=df[-4:-1].sum这样的公式可以在一行代码中解决问题.但是,那没有用.没有显式汇总所有列,有没有办法做到?

I guess you could use df['Apples'] + df['Bananas'] and so on, but my actual dataframe is much larger than this. I was hoping a formula like df['Fruit Total']=df[-4:-1].sum could do the trick in one line of code. That didn't work however. Is there any way to do it without explicitly summing up all columns?

推荐答案

您可以先通过 sum :

You can first select by iloc 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

所有列的总和为:

df['Fruit Total']= df.sum(axis=1)

这篇关于 pandas :将多列汇总为一列而没有最后一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆