我有两个数据框,一个有更多列(但其中两个很重要),第二个有两列。 DF1:
col_a col_b
101 104
102 201
103 301
505 601
DF2:
col_a_a col_b_b
420 637
425 643
201 701
601 702
我需要接下来的事情。查看df1['col_b']
,如果df2['col_a_a']
中存在,则将其替换为df2['col_b_b']
。
我尝试了两种方法:
df1['col_b'] = np.where(df1['col_b'] == df2['col_a_a'], df2['col_b_b'], df1['col_b'])
df1.col_b[df1.col_b == df2.col_a_a] = df2.col_b_b
但他们两个都给我带来了同样的错误:ValueError: Can only compare identically-labeled Series objects
期望的输出:
col_a col_b
101 104
102 701
103 301
505 702
答案 0 :(得分:2)
使用replace
创建的Series
{/ 3}}:
df1['col_b'] = df1['col_b'].replace(df2.set_index('col_a_a')['col_b_b'])
print (df1)
col_a col_b
0 101 104
1 102 701
2 103 301
3 505 702
答案 1 :(得分:1)
另一种方法,使用pd.Series.map
:
df1['col_b'] = df1['col_b'].map(df2.set_index('col_a_a')['col_b_b']).fillna(df1['col_b'])
根据您的数据,这可能会更有效。