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

数据集合并键选择及双国家列匹配索引的最优方案咨询

解决方案:为双国家列匹配Index的高效方法

你不需要反复修改匹配键再合并,有两种更高效的处理方式,以Python pandas为例:

原始数据(Markdown格式呈现)

FDI数据集

origindestinationFDI
USUK120
ITAUS90
TRSPA40

国家Index数据集

CountryIndex
ITA0
UK1
TR0
SPA1

方法一:两次merge(直观易理解)

直接分别按origin和destination与国家表合并,每次合并指定匹配键并命名新列,避免列名冲突:

import pandas as pd

# 创建原始DataFrame
fdi_df = pd.DataFrame({
    'origin': ['US', 'ITA', 'TR'],
    'destination': ['UK', 'US', 'SPA'],
    'FDI': [120, 90, 40]
})

index_df = pd.DataFrame({
    'Country': ['ITA', 'UK', 'TR', 'SPA'],
    'Index': [0, 1, 0, 1]
})

# 第一次合并:匹配origin的Index
result = fdi_df.merge(index_df, left_on='origin', right_on='Country', how='left')
result = result.rename(columns={'Index': 'origin_index'}).drop('Country', axis=1)

# 第二次合并:匹配destination的Index
result = result.merge(index_df, left_on='destination', right_on='Country', how='left')
result = result.rename(columns={'Index': 'destination_index'}).drop('Country', axis=1)

最终结果:

origindestinationFDIorigin_indexdestination_index
USUK120NaN1
ITAUS900NaN
TRSPA4001

方法二:用map函数(更简洁高效)

把国家Index表转换成字典,直接用map给两列批量匹配:

# 转换为字典:{国家: Index}
country_index_dict = index_df.set_index('Country')['Index'].to_dict()

# 给两列匹配Index
fdi_df['origin_index'] = fdi_df['origin'].map(country_index_dict)
fdi_df['destination_index'] = fdi_df['destination'].map(country_index_dict)

得到的结果和方法一完全一致,这种方式代码更短,适合数据量较大的场景。

补充说明

  • 对于匹配不到的国家(比如示例中的US),结果会显示NaN,你可以根据需求用fillna()填充默认值,或者用dropna()过滤掉这些行。
  • 如果使用其他工具(比如R的dplyr),逻辑类似:要么两次join,要么用字典映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:45:44