gpt4 book ai didi

python - 对 Pandas 数据框底部的行求和

转载 作者:行者123 更新时间:2023-12-04 07:43:06 25 4
gpt4 key购买 nike

尝试对 Pandas 中特定列的行求和。
有:

df =

name age gender sales commissions
joe 25 m 100 10
jane 55 f 40 4
想:
df =
name age gender sales commissions
joe 25 m 100 10
jane 55 f 40 4

Total 140 14
我试过这个选项,但它汇总了所有内容:
df.loc['Total'] = df.sum()

最佳答案

您只能对感兴趣的列求和:

## recreate your data
df = pd.DataFrame({'name':['joe','jane'],'age':[25,55],'sales':[100,40],'commissions':[10,4]})

df.loc['Total'] = df[['sales','commissions']].sum()
结果:
>>> df
name age sales commissions
0 joe 25.0 100.0 10.0
1 jane 55.0 40.0 4.0
Total NaN NaN 140.0 14.0
如果不想出现 NaN,可以用空字符串替换它们: df = df.fillna('')结果:
>>> df
name age sales commissions
0 joe 25.0 100.0 10.0
1 jane 55.0 40.0 4.0
Total 140.0 14.0

关于python - 对 Pandas 数据框底部的行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67351366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com