1

I have a dictionary which looks like this: di = {1: "A", 2: "B"}

I would like to apply it to the "col3" column of a dataframe similar to using value in "col1" as key to di:

     col1   col2   col3
0       w      a     U
1       1      2     V
2       2    NaN     W

to get:

     col1   col2   col3
0       w      a     U
1       1      2     A
2       2    NaN     B

How can I best do this? All answers I found were to replace columns considering them as keys.

Community
  • 1
  • 1
harshit
  • 3,628
  • 3
  • 28
  • 54

1 Answers1

2

You can do the mapping on col1 and fill the missing values with the values in col3:

df.col3 = df.col1.map(di).fillna(df.col3)
ayhan
  • 64,199
  • 17
  • 170
  • 189