如何在存在重复键时用一个DataFrame列更新另一个DataFrame的列?
解决带重复键的DataFrame列更新问题
问题背景
我有两个DataFrame,二者的Employee ID列都存在重复值(这是可接受的)。我希望用源DataFrame中的Product列更新目标DataFrame的Product列,但使用.update()方法时因重复值报错,能否一步实现该操作?
需求是让目标df的Product列与源df完全一致,通过源文件更新目标文件,因为键对应的Product会随时间变化,所以需要执行此更新操作。
解决方案
.update()要求索引唯一,而你的场景存在重复键,因此可以用以下两种更适配的方式实现:
情况1:两个DataFrame的行顺序完全对应(Employee ID的顺序和重复次数一致)
这种场景下直接赋值即可一步完成更新:
target_df['Product'] = source_df['Product']
情况2:行顺序不一致,需按Employee ID匹配更新
如果两个DataFrame的行顺序不同,但需要根据Employee ID匹配更新Product值,先构建ID到Product的映射(利用去重确保每个ID对应唯一值),再用map方法更新:
# 构建Employee ID到Product的映射(去重避免重复键冲突) product_map = source_df.drop_duplicates('Employee ID').set_index('Employee ID')['Product'] # 匹配更新目标df的Product列 target_df['Product'] = target_df['Employee ID'].map(product_map)
完整示例验证
import pandas as pd source = { "Employee ID": [123, 456, 456, 123], "Product": ['abc', 'def', 'def', 'abc']} target = { "Employee ID": [123, 456, 456, 123], "Product": ['jkl', 'mno', 'pqr', 'stu']} source_df = pd.DataFrame(source) target_df = pd.DataFrame(target) # 执行情况1的更新 target_df['Product'] = source_df['Product'] print(target_df) # 输出结果与预期一致: # Employee ID Product # 0 123 abc # 1 456 def # 2 456 def # 3 123 abc # 模拟行顺序打乱的情况2 target_shuffled = { "Employee ID": [456, 123, 123, 456], "Product": ['mno', 'jkl', 'stu', 'pqr']} target_shuffled_df = pd.DataFrame(target_shuffled) product_map = source_df.drop_duplicates('Employee ID').set_index('Employee ID')['Product'] target_shuffled_df['Product'] = target_shuffled_df['Employee ID'].map(product_map) print(target_shuffled_df) # 输出: # Employee ID Product # 0 456 def # 1 123 abc # 2 123 abc # 3 456 def
为什么.update()会报错
.update()是基于索引进行更新的方法,要求索引必须唯一。当存在重复索引时,无法确定唯一的更新位置,因此会抛出ValueError: cannot merge on duplicate keys,而上述两种方法避开了索引唯一的限制,更适配你的重复键场景。
内容的提问来源于stack exchange,提问作者Yogesh Riyat
相关产品推荐
相关产品推荐

