You need to enable JavaScript to run this app. 如何使用映射关系填充pandas DataFrame中的NaN或Null缺失值
优惠活动
大模型
产品
解决方案
定价
更多

如何使用映射关系填充pandas DataFrame中的NaN或Null缺失值

pandas 实现 Excel VLOOKUP 匹配填充缺失值的方案

你需要实现的是用已有的「国家-大洲」对应关系,填充continent列的缺失值,和Excel VLOOKUP逻辑完全一致,具体实现步骤如下:

  • 第一步:导入依赖并构造示例数据
import pandas as pd

# 示例原始数据
df = pd.DataFrame([
    ["North America", "Canada"],
    [None, "Canada"],
    [None, "Canada"],
    [None, "Nigeria"],
    ["Africa", "Nigeria"],
], columns=["continent", "country"])
  • 第二步:生成VLOOKUP对应的匹配映射表
    从现有数据中提取非空、唯一的国家-大洲对应关系,作为匹配基准,相当于VLOOKUP里的查找区域:
country_continent_map = df.dropna(subset=['continent']) \
                          .drop_duplicates(subset=['country']) \
                          .set_index('country')['continent']
  • 第三步:填充continent列的缺失值
# 按国家匹配对应大洲,填充空值,和VLOOKUP逻辑完全一致
df['continent'] = df['continent'].fillna(df['country'].map(country_continent_map))

运行后所有空的continent字段都会被正确填充:加拿大对应北美洲、尼日利亚对应非洲。如果存在部分国家在现有映射中找不到对应值的情况,填充后仍会保留空值,你可以手动补充country_continent_map里的对应关系后再重新运行填充逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 04:18:02