如何对pandas DataFrame指定列的行值求和并去除原行索引
Pandas 对DataFrame各列求和并重置行索引
现有数据
当前持有的df_new结构如下:
Col2 Col3 0 5 8 1 1 0 2 3 5 3 4 1 4 0 7
初始构造代码:
import pandas as pd df = pd.DataFrame() df["Col1"] = [0,2,4,6,2] df["Col2"] = [5,1,3,4,0] df["Col3"] = [8,0,5,1,7] df["Col4"] = [1,4,6,0,8] df_new = df.iloc[:, 1:3]
目标结果
对所有列的数值求和,去除原有行索引,得到单行的汇总结果:
Col2 Col3 13 21
实现代码
# 按列求和后转置为单行DataFrame df_result = df_new.sum().to_frame().T # 打印时如果需要隐藏默认行索引,可使用以下写法 print(df_result.to_string(index=False))
代码说明
df_new.sum():默认沿列方向计算总和,返回索引为原列名、值为对应列汇总值的Series对象.to_frame().T:先将Series转为DataFrame,再做转置,得到和原表列结构一致的单行汇总表,不会保留原数据的行索引
运行后输出和预期完全一致:
Col2 Col3 13 21
内容的提问来源于stack exchange,提问作者Serdia
相关产品推荐
相关产品推荐

