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

如何基于单向贸易的Pandas DataFrame生成净贸易DataFrame?

自动化生成国家间净贸易额DataFrame的方法

场景还原

现有记录双边出口量的DataFrame df1,数据结构如下:

import pandas as pd

df1 = pd.DataFrame({
    'Country1': ['A', 'B', 'A'],
    'Country2': ['B', 'A', 'C'],
    'Value': [3, 5, 3]
})

我们需要生成df2,展示任意两国间的净贸易额(例如A→C净贸易额为3,B→A为2),且支持大量国家的自动化处理。

解决方案

核心思路是通过匹配反向贸易数据,自动计算每个国家对的净出口额,无需手动处理单一对国家。

方法一:合并反向数据计算净贸易额

# 创建反向贸易数据(交换Country1和Country2,重命名价值列)
reverse_df = df1.rename(columns={
    'Country1': 'Country2',
    'Country2': 'Country1',
    'Value': 'Reverse_Value'
})

# 合并原数据与反向数据,填充缺失值为0(代表无反向贸易)
merged_df = df1.merge(reverse_df, on=['Country1', 'Country2'], how='outer').fillna(0)

# 计算净贸易额:当前方向出口量 - 反向出口量
merged_df['Net_Value'] = merged_df['Value'] - merged_df['Reverse_Value']

# 整理df2,保留核心列并过滤无贸易的国家对(可选)
df2 = merged_df[['Country1', 'Country2', 'Net_Value']].reset_index(drop=True)
df2 = df2[df2['Net_Value'] != 0]

方法二:分组计算(适合需要统一国家对标识的场景)

如果需要将A→B和B→A视为同一组,先生成排序后的国家配对键,再聚合计算:

# 生成排序后的国家配对(如A-B和B-A统一为('A','B'))
df1['pair'] = df1.apply(lambda row: tuple(sorted([row['Country1'], row['Country2']])), axis=1)

# 按配对和出口方向聚合数据
pivot_df = df1.pivot_table(
    index='pair',
    columns='Country1',
    values='Value',
    fill_value=0
).reset_index()

# 拆分配对为国家列,计算指定方向的净贸易额
pivot_df['Country1'] = pivot_df['pair'].str[0]
pivot_df['Country2'] = pivot_df['pair'].str[1]
# 示例:计算B→A的净贸易额 = B出口到A的量 - A出口到B的量
pivot_df['Net_Value'] = pivot_df.get('B', 0) - pivot_df.get('A', 0)

# 整理df2
df2 = pivot_df[['Country1', 'Country2', 'Net_Value']].reset_index(drop=True)

结果验证

运行方法一的代码后,df2的输出结果为:

Country1Country2Net_Value
AB-2
BA2
AC3

完全符合需求中的示例(B→A净贸易额为2,A→C为3)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 17:46:31