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

按条件修改Pandas DataFrame的nativeCountry列值为大洲未生效如何解决

问题原因
  • adult_quasiIdentifier是其他DataFrame的切片视图而非独立对象,pandas的安全机制会阻止对视图的直接修改,触发SettingWithCopyWarning,导致修改不生效。
  • 循环遍历逐批替换的写法不符合pandas的最佳实践,执行效率极低。
修复方案
  1. 先将数据集转为独立副本,规避视图修改限制
adult_quasiIdentifier = adult_quasiIdentifier.copy()
  1. 构造「国家-大洲」映射字典,使用map方法批量替换,性能远高于循环写法
# 反转现有大洲-国家映射,生成国家为键、大洲为值的映射字典
country_continent_map = {}
for continent, countries in contient.items():
    for country in countries:
        country_continent_map[country] = continent

# 批量替换国家为对应大洲,未匹配到的国家默认填充为Other,可按需修改默认值
# 如果国家名存在前后空格的问题,可在map前加.str.strip()处理
adult_quasiIdentifier['nativeCountry'] = adult_quasiIdentifier['nativeCountry'].map(country_continent_map).fillna('Other')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:36:05