温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Changing value of cell in one dataframe based on comparision another cell to another dataframe's cel
dataframe pandas python

python - 基于将另一个单元格与另一个数据帧的cel进行比较来更改一个数据帧中的单元格的值

发布于 2020-03-29 21:41:43

我有两个看起来像的数据框:

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 可以改善我的代码。你有什么想法吗?

查看更多

提问者
maliniaki
被浏览
18
jezrael 2020-01-31 18:33

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'])