【问题标题】:adding column total and mean to DataFrame将列总数和平均值添加到 DataFrame
【发布时间】:2021-09-30 06:06:24
【问题描述】:
我有一个如下所示的数据框,我想要最后一行中 col1 的总和以及 col2 和 col3 的平均值。
col1 col2 col3
1 3 1
3 4 1
3 5 2
1 1 3
2 2 4
3 1 9
2 3 5
2 5 6
total 17.0 3.0 3.8
请帮忙。
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
将DataFrame.agg 与DataFrame.loc 一起使用:
.agg 函数会聚合数据,它可以聚合求和,意味着一次调用。
.loc 将添加具有给定索引的新行。
df.loc['new'] = df.agg({'col1':'sum', 'col2':'mean', 'col3':'mean'})
print (df)
col1 col2 col3
0 1.0 3.0 1.000
1 3.0 4.0 1.000
2 3.0 5.0 2.000
3 1.0 1.0 3.000
4 2.0 2.0 4.000
5 3.0 1.0 9.000
6 2.0 3.0 5.000
7 2.0 5.0 6.000
new 17.0 3.0 3.875