Pandas: sum up multiple columns into one column without last column( 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?
推荐答案
可以先通过 iloc
然后是 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 :将多列汇总为一列,没有最后一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pandas :将多列汇总为一列,没有最后一列
- python-m http.server 443--使用SSL? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 沿轴计算直方图 2022-01-01