目标
我有一个 Pandas 数据框,如下所示,它有多个列,并且想要获取列的总数,MyColumn.
MyColumn
数据框 -df:
df
print df
X MyColumn Y Z 0 A 84 13.0 69.0 1 B 76 77.0 127.0 2 C 28 69.0 16.0 3 D 28 28.0 31.0 4 E 19 20.0 85.0 5 F 84 193.0 70.0
我的尝试 :
我试图使用groupbyand得到列的总和.sum():
groupby
.sum()
Total = df.groupby['MyColumn'].sum() print Total
这会导致以下错误:
TypeError: 'instancemethod' object has no attribute '__getitem__'
预期产出
我预计输出如下:
319
或者,我想用一个包含总数df的新row标题进行编辑:TOTAL
row
TOTAL
X MyColumn Y Z 0 A 84 13.0 69.0 1 B 76 77.0 127.0 2 C 28 69.0 16.0 3 D 28 28.0 31.0 4 E 19 20.0 85.0 5 F 84 193.0 70.0 TOTAL 319
你应该使用sum:
sum
Total = df['MyColumn'].sum() print (Total) 319
然后使用locwith Series,在这种情况下,索引应设置为与您需要求和的特定列相同:
loc
Series
df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn']) print (df) X MyColumn Y Z 0 A 84.0 13.0 69.0 1 B 76.0 77.0 127.0 2 C 28.0 69.0 16.0 3 D 28.0 28.0 31.0 4 E 19.0 20.0 85.0 5 F 84.0 193.0 70.0 Total NaN 319.0 NaN NaN
因为如果你传递标量,所有行的值都将被填充:
df.loc['Total'] = df['MyColumn'].sum() print (df) X MyColumn Y Z 0 A 84 13.0 69.0 1 B 76 77.0 127.0 2 C 28 69.0 16.0 3 D 28 28.0 31.0 4 E 19 20.0 85.0 5 F 84 193.0 70.0 Total 319 319 319.0 319.0
其他两个解决方案是at,ix请参阅下面的应用程序:
at
ix
df.at['Total', 'MyColumn'] = df['MyColumn'].sum() print (df) X MyColumn Y Z 0 A 84.0 13.0 69.0 1 B 76.0 77.0 127.0 2 C 28.0 69.0 16.0 3 D 28.0 28.0 31.0 4 E 19.0 20.0 85.0 5 F 84.0 193.0 70.0 Total NaN 319.0 NaN NaN
df.ix['Total', 'MyColumn'] = df['MyColumn'].sum() print (df) X MyColumn Y Z 0 A 84.0 13.0 69.0 1 B 76.0 77.0 127.0 2 C 28.0 69.0 16.0 3 D 28.0 28.0 31.0 4 E 19.0 20.0 85.0 5 F 84.0 193.0 70.0 Total NaN 319.0 NaN NaN
注意: 自 Pandas v0.20 起,ix已弃用。使用loc或iloc代替。
iloc