如何基于另一个Pandas DataFrame替换某列的值?
按主键更新DataFrame指定列的解决方案
需求说明:
- 以
col1作为主键,用df2中的col2值覆盖df1中对应主键行的col2 - 保留df1中原有的
col3值不变
方法一:使用update方法(推荐)
update方法会根据索引匹配,用另一个DataFrame的值更新当前DataFrame,非常适合这种按主键更新指定列的场景:
import pandas as pd # 构建原始DataFrame d1 = {'col1': ['1', '2','3','4'], 'col2': [12, 34,56,78],'col3':[100,200,300,400]} df1 = pd.DataFrame(data=d1) d2 = {'col1': ['2','3'], 'col2': [1984,4891],'col3':[500,600]} df2 = pd.DataFrame(data=d2) # 按主键更新col2 # 先将col1设为索引,确保匹配主键 df_updated = df1.set_index('col1') # 用df2的col2更新df_updated的col2 df_updated['col2'].update(df2.set_index('col1')['col2']) # 恢复原索引 df_final = df_updated.reset_index() print(df_final)
运行后输出结果:
col1 col2 col3 0 1 12 100 1 2 1984 200 2 3 4891 300 3 4 78 400
方法二:使用merge结合fillna
如果不想修改索引结构,可以用合并的方式实现:
import pandas as pd # 构建原始DataFrame d1 = {'col1': ['1', '2','3','4'], 'col2': [12, 34,56,78],'col3':[100,200,300,400]} df1 = pd.DataFrame(data=d1) d2 = {'col1': ['2','3'], 'col2': [1984,4891],'col3':[500,600]} df2 = pd.DataFrame(data=d2) # 合并两个DataFrame,仅关联df2的主键和目标列 merged = df1.merge(df2[['col1', 'col2']], on='col1', how='left', suffixes=('', '_df2')) # 用df2的col2值覆盖匹配行,未匹配行保留原数据 merged['col2'] = merged['col2_df2'].fillna(merged['col2']) # 删除临时生成的辅助列 df_final = merged.drop('col2_df2', axis=1) print(df_final)
该方法同样能得到目标结果,适合需要维持原索引逻辑的场景。
内容的提问来源于stack exchange,提问作者user27286
相关产品推荐
相关产品推荐

