如何基于Product列将DF2的Product type填充到DF1对应列?
解决方案
你可以用map()函数直接填充DF1的现有列,完全不会新增冗余列,步骤如下:
从DF2创建产品类型映射字典
把DF2的Product列作为键,Product type列作为值,生成匹配用的字典:product_type_map = DF2.set_index('Product')['Product type'].to_dict()填充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
相关产品推荐
相关产品推荐

