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

如何在单个DataFrame中实现类似Excel VLOOKUP的功能?

Pandas实现类似Excel VLOOKUP功能生成父级名称列

要给现有DataFrame新增parent_name列,实现类似Excel中VLOOKUP的匹配效果,可以用以下两种Pandas方法:

方法一:使用map()函数

先从原数据构建「编码-名称」的映射字典,再通过字典匹配parent_code得到对应的父级名称:

# 构建child_code到child_name的映射字典
code_name_mapping = df.set_index('child_code')['child_name'].to_dict()

# 匹配parent_code,将无匹配项(如0)替换为空字符串
df['parent_name'] = df['parent_code'].map(code_name_mapping).fillna('')

说明:set_index('child_code')['child_name'].to_dict()把child_code作为键、child_name作为值生成映射关系;map()会自动根据parent_code查找对应名称,找不到的项返回NaN,最后用fillna('')将空值替换为空白字符串。

方法二:使用merge()函数

通过左连接将DataFrame与自身关联,用parent_code匹配child_code来获取父级名称:

# 左连接自身,关联parent_code和child_code
merged_df = df.merge(
    df[['child_code', 'child_name']],
    left_on='parent_code',
    right_on='child_code',
    how='left',
    suffixes=('', '_parent')
)

# 生成parent_name列并清理冗余列
merged_df['parent_name'] = merged_df['child_name_parent'].fillna('')
merged_df.drop(columns=['child_code_parent', 'child_name_parent'], inplace=True)

# 替换原df(可选)
df = merged_df

说明:merge()的how='left'确保原DataFrame的所有行都被保留;suffixes参数避免关联后列名重复;最后将匹配到的父级名称赋值给parent_name,并删除中间生成的冗余列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 18:58:12