You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 02:15:39