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

如何基于Product列将DF2的Product type填充到DF1对应列?

解决方案

你可以用map()函数直接填充DF1的现有列,完全不会新增冗余列,步骤如下:

  1. 从DF2创建产品类型映射字典
    把DF2的Product列作为键,Product type列作为值,生成匹配用的字典:

    product_type_map = DF2.set_index('Product')['Product type'].to_dict()
    
  2. 填充DF1的Product type列
    用DF1的Product列匹配映射字典,直接赋值给原有的空列:

    DF1['Product type'] = DF1['Product'].map(product_type_map)
    

特殊情况处理

如果DF1中存在DF2未收录的产品,map()会返回NaN,要是想保留原列的空值(而非替换成NaN),可以加上fillna():

DF1['Product type'] = DF1['Product'].map(product_type_map).fillna(DF1['Product type'])

替代方案(基于merge但清理临时列)

如果你更习惯用merge(),可以合并后覆盖原列再删除临时生成的列:

# 只合并需要的列,避免引入多余数据
DF1 = DF1.merge(DF2[['Product', 'Product type']], on='Product', how='left', suffixes=('', '_temp'))
# 用临时列覆盖原列
DF1['Product type'] = DF1['Product type_temp']
# 删除临时列
DF1.drop('Product type_temp', axis=1, inplace=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:36:41