如何在Pandas DataFrame末尾添加含col1求和、col2和col3均值的汇总行
实现代码
import pandas as pd # 构造示例DataFrame(如果已经有对应DataFrame可直接跳过这一步) df = pd.DataFrame({ 'col1': [1,3,3,1,2,3,2,2], 'col2': [3,4,5,1,2,1,3,5], 'col3': [1,1,2,3,4,9,5,6] }) # 按需求计算各列汇总值 summary_row = df.agg({ 'col1': 'sum', 'col2': 'mean', 'col3': 'mean' }).round(1) # 按需求保留1位小数,可自行调整精度规则 # 将汇总行添加到DataFrame末尾,行索引设为total df.loc['total'] = summary_row # 打印输出结果 print(df)
输出效果
col1 col2 col3 0 1.0 3.0 1.0 1 3.0 4.0 1.0 2 3.0 5.0 2.0 3 1.0 1.0 3.0 4 2.0 2.0 4.0 5 3.0 1.0 9.0 6 2.0 3.0 5.0 7 2.0 5.0 6.0 total 17.0 3.0 3.9
可选调整方案
- 如果你需要和示例中col3显示3.8的效果一致,可以修改小数处理逻辑为截断保留1位:
summary_row['col3'] = float(f"{summary_row['col3']:.1f}") - 如果你不想修改原DataFrame的整数索引,可以用concat方法拼接汇总行:
summary_df = pd.DataFrame([summary_row], index=['total']) df_with_total = pd.concat([df, summary_df], ignore_index=False)
内容的提问来源于stack exchange,提问作者DataGuy
相关产品推荐
相关产品推荐

