Pandas中如何按匹配索引用另一DataFrame列值替换目标列值?
解决方法
你的需求是按索引匹配替换,pd.replace()返回NA是因为它默认是基于值的替换逻辑,无法直接按索引精准匹配替换目标值。下面是两种可行的实现方式:
方法一:使用DataFrame.update()
这个方法会直接在df2上按索引匹配更新,仅替换索引重叠的部分,不影响其他行:
import pandas as pd # 构造示例数据 df1 = pd.DataFrame({'Home': ['MS', 'KM', 'RR'], 'Place': ['Z2', 'Z3', 'R2']}, index=['a', 'c', 'd']) df2 = pd.DataFrame({'Place1': ['A2', 'A66', 'F32', 'K41', 'E90']}, index=['a', 'c', 'z', 'x', 't']) # 按索引匹配替换 df2['Place1'].update(df1['Place']) print(df2)
执行后输出符合预期:
Place1 a Z2 c Z3 z F32 x K41 t E90
方法二:使用Series.combine_first()
这个方法会返回新的结果集,优先取df1['Place']的匹配值,无匹配项则保留df2['Place1']的值:
import pandas as pd # 构造示例数据 df1 = pd.DataFrame({'Home': ['MS', 'KM', 'RR'], 'Place': ['Z2', 'Z3', 'R2']}, index=['a', 'c', 'd']) df2 = pd.DataFrame({'Place1': ['A2', 'A66', 'F32', 'K41', 'E90']}, index=['a', 'c', 'z', 'x', 't']) # 生成结果并过滤出df2原索引 result = df1['Place'].combine_first(df2['Place1']).to_frame('Place1').loc[df2.index] print(result)
内容的提问来源于stack exchange,提问作者MMJJ
相关产品推荐
相关产品推荐

