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

如何在Pandas DataFrame中用Americas行减SouthAmerica行并新增NorthAmerica行?

用Pandas的groupby和diff实现区域数据差值计算并添加新行

原始数据

创建DataFrame的代码:

import pandas as pd
df = pd.DataFrame({
    "country": ["Americas", "Americas","Europe", "Europe", "SouthAmerica", "SouthAmerica"],
    "year": [2000, 2005, 2000, 2005, 2000, 2005],
    "planted": [900, 800, 300, 100, 500, 300],
    "regrowth": [300, 400, 500, 200, 200, 100]
})

实际数据展示:

country  year  planted  regrowth
0      Americas  2000      900       300
1      Americas  2005      800       400
2        Europe  2000      300       500
3        Europe  2005      100       200
4  SouthAmerica  2000      500       200
5  SouthAmerica  2005      300       100

需求

计算Americas与SouthAmerica在planted和regrowth列的差值(Americas数值 - SouthAmerica数值),把结果作为NorthAmerica行添加到原DataFrame末尾,最终输出如下:

country  year  planted  regrowth
0      Americas  2000      900       300
1      Americas  2005      800       400
2        Europe  2000      300       500
3        Europe  2005      100       200
4  SouthAmerica  2000      500       200
5  SouthAmerica  2005      300       100
6  NorthAmerica  2000      400       100
7  NorthAmerica  2005      500       300

解决方案(基于groupby+diff)

步骤1:筛选目标区域并排序

先把Americas和SouthAmerica的数据筛出来,按年份升序、国家名称降序排序——这样每个年份组里,Americas会排在SouthAmerica前面,方便后续计算差值。

target_df = df[df['country'].isin(['Americas', 'SouthAmerica'])].sort_values(['year', 'country'], ascending=[True, False])

步骤2:分组计算差值

按year分组后,对planted和regrowth列用diff(-1)方法。diff(-1)是计算当前行和下一行的差值,刚好能得到每个年份里Americas减SouthAmerica的结果。

diff_result = target_df.groupby('year')[['planted', 'regrowth']].diff(-1)

步骤3:构造NorthAmerica数据

把差值结果里的空值(NaN)删掉,添加country列(值为NorthAmerica)和year列,最后调整列顺序和原DataFrame一致:

north_america = diff_result.dropna().reset_index(drop=True)
north_america['country'] = 'NorthAmerica'
north_america['year'] = [2000, 2005]
north_america = north_america[['country', 'year', 'planted', 'regrowth']]

步骤4:合并到原DataFrame

用concat把新构造的NorthAmerica数据追加到原DataFrame后面,重置索引得到连续的序号:

final_df = pd.concat([df, north_america], ignore_index=True)

完整可运行代码

import pandas as pd

# 原始数据
df = pd.DataFrame({
    "country": ["Americas", "Americas","Europe", "Europe", "SouthAmerica", "SouthAmerica"],
    "year": [2000, 2005, 2000, 2005, 2000, 2005],
    "planted": [900, 800, 300, 100, 500, 300],
    "regrowth": [300, 400, 500, 200, 200, 100]
})

# 筛选并排序目标区域数据
target_df = df[df['country'].isin(['Americas', 'SouthAmerica'])].sort_values(['year', 'country'], ascending=[True, False])

# 按年份分组计算差值
diff_result = target_df.groupby('year')[['planted', 'regrowth']].diff(-1)

# 构造NorthAmerica数据
north_america = diff_result.dropna().reset_index(drop=True)
north_america['country'] = 'NorthAmerica'
north_america['year'] = [2000, 2005]
north_america = north_america[['country', 'year', 'planted', 'regrowth']]

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

关键逻辑说明

  • 排序是为了保证每个年份内,要被减数(Americas)排在减数(SouthAmerica)前面,这样diff(-1)就能直接得到我们需要的差值。
  • groupby('year')确保差值计算是在同一年份内进行,不会出现跨年份的错误计算。
  • diff(-1)和默认的diff()(当前行减上一行)方向相反,这里用它刚好匹配我们“前减后”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:25:13