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

如何在Pandas DataFrame中添加首末行差值的汇总行?

实现Pandas添加首尾行差值汇总行的最优方法

推荐方案:使用pd.concat(官方推荐,避免弃用警告)

这是Pandas 2.0+的最佳实践方案,append方法已被标记为弃用,concat逻辑清晰且更稳定。

步骤如下:

  1. 提取首尾行的数值列,计算差值
  2. 构造包含汇总信息的单行DataFrame
  3. 将原DataFrame与单行DataFrame合并

示例代码:

import pandas as pd

data = [
    ['A',1,5],
    ['B',2,4],
    ['C',3,3],
    ['D',4,2],
    ['E',5,1],
    ['F',6,0]
]
df = pd.DataFrame(data, columns=['name','x','y'])

# 构造差值行的DataFrame
diff_row = pd.DataFrame({
    'name': ['diff'],
    'x': [df['x'].iloc[-1] - df['x'].iloc[0]],
    'y': [df['y'].iloc[-1] - df['y'].iloc[0]]
})

# 合并得到最终结果
df_with_diff = pd.concat([df, diff_row], ignore_index=True)
print(df_with_diff)

旧版本兼容方案:使用append(不推荐)

如果你的Pandas版本低于2.0,可临时用append方法,但官方后续会移除该功能,不建议长期使用:

# 仅适用于Pandas 2.0以下版本
diff_series = pd.Series({
    'name': 'diff',
    'x': df['x'].iloc[-1] - df['x'].iloc[0],
    'y': df['y'].iloc[-1] - df['y'].iloc[0]
})
df_with_diff = df.append(diff_series, ignore_index=True)

内容的提问来源于stack exchange,提问作者lucky1928

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:02:52