edn
edn

Reputation: 2183

How to conditionally replace Pandas dataframe column values from another dataframe

I have the following 2 dataframes:

df1 = pd.DataFrame({"col1":[1, 2, 3],
                    "col2":["a", "b", "c"]})

df1

Output:

    col1    col2
0   1       a
1   2       b
2   3       c

And the second one:

df2 = pd.DataFrame({"col1":[1, 2, 3, 4, 5],
                    "col2":["x", "y", "z", "q", "w"]})
df2

Output:

    col1    col2
0   1       x
1   2       y
2   3       z
3   4       q
4   5       w

Additional info: col1 in both data frames have unique values. col2 does not necessarily have unique values.

What to achieve: How can I replace values of col2 in df1 with the corresponding col2 values from df2 from the matching col1 values?

Desired final content of df1 is supposed to be as following:

    col1    col2
0   1       x
1   2       y
2   3       z

Upvotes: 1

Views: 149

Answers (2)

Epsi95
Epsi95

Reputation: 9047

try .map

df1['col2'] = df1['col1'].map(df2.set_index('col1')['col2'])

#   col1    col2
# 0 1   x
# 1 2   y
# 2 3   z

Upvotes: 1

wwnde
wwnde

Reputation: 26676

Create dict by zipping the df2 columns. Use map to transfer values over to df1. Code below

df1['col2']=df1['col1'].map(dict(zip(df2['col1'],df2['col2'])))

Upvotes: 1

Related Questions