我有两个看起来像的数据框:
df1
col1 col2 col3
20 John Positive
21 Kate Negative
22 Nick Another
df2
col1 col2 col3
21 message white
22 text black
20 nothing orange,yellow
19 excel blue
我想让它们看起来像:
df3
col1 col2 col3
20 John orange,yellow
21 Kate white
22 Nick black
如果两个数据帧的col1中的数字匹配,我想将col3中df1的值更改为col3中df2的值。(在col1的df2中,我获得的值比df1 col1中的更多,但它包括df1 col1中的所有数字)
我提出了解决方案,如下所示:
for i in range(len(df2)):
df1.loc[df1.col1 == df2.col1[i], ['col3']] = df2.col3[i]
我的解决方案正在工作,但这确实很耗时。我希望使用 pandas 可以改善我的代码。你有什么想法吗?
DataFrame.merge
与左联接一起使用DataFrame.fillna
:
#column fo join with all columns for replace, here col3
cols = ['col1','col3']
df = df1.merge(df2[cols], on='col1', how='left', suffixes=('_','')).fillna(df1)[df1.columns]
print (df)
col1 col2 col3
0 20 John orange,yellow
1 21 Kate white
2 22 Nick black
或Series.map
按系列使用,df2
如果replace
只需要一列:
df1['col3'] = df1['col1'].map(df2.set_index('col1')['col3']).fillna(df1['col3'])
要么:
df1['col3'] = df1['col1'].replace(df2.set_index('col1')['col3']).fillna(df1['col3'])