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

使用Pandas基于国家-地区映射替换国籍列为所属地区

解决方案:将nationality列替换为对应region

你写的循环代码问题出在:遍历df["nationality"]时,value是列中的字符串值,调用value.index是操作字符串的索引方法,而非DataFrame的行索引,自然拿不到对应行的region值,这就是代码跑不起来的原因。

下面给你几个简单可行的方案,基于country和nationality值完全匹配的前提(你的数据示例符合这个条件):

方法1:构建映射字典后用map批量替换

先提取country到region的唯一映射关系,再替换nationality列:

# 生成country→region的映射字典(去重避免重复键)
country_to_region = df.drop_duplicates(subset=['country']).set_index('country')['region'].to_dict()

# 替换nationality列
df['nationality'] = df['nationality'].map(country_to_region)

方法2:直接用replace方法替换

和方法1原理一致,直接用映射字典完成替换:

country_to_region = df.drop_duplicates(subset=['country']).set_index('country')['region'].to_dict()
df['nationality'] = df['nationality'].replace(country_to_region)

方法3:处理不匹配的特殊情况(可选)

如果nationality中存在和country不匹配的值,可以用fillna保留原内容,或替换为指定值:

# 不匹配时保留原nationality值
df['nationality'] = df['nationality'].map(country_to_region).fillna(df['nationality'])

# 或者替换为"Unknown"
# df['nationality'] = df['nationality'].map(country_to_region).fillna('Unknown')

用你的数据示例测试,运行后结果如下:

countryregionnationality
FranceEuropeEurope
IrakMiddle-EastMiddle-East

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 02:17:14