对 Pandas 数据框底部的行求和

Sum Rows at Bottom of Pandas Dataframe

正在尝试对 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