0

I have the following Data Frame:

Company ID    Company Name    State
100           Apple           CA
100           Apl             CA
200           Amazon          WA
200           Amz             WA
300           Oracle          CA
300           Oracle          CA

And the following dictionary:

{100: "Apple, Inc.", 200: "Amazon, Inc."}

*Note that Oracle isn't in the dictionary

What I want to do is replace the values in the Company Name column with the dictionary value if the key is present in the Company ID column, otherwise leave the value the same. So the output would be:

Company ID    Company Name    State
100           Apple, Inc.     CA
100           Apple, Inc.     CA
200           Amazon, Inc.    WA
200           Amazon, Inc.    WA
300           Oracle          CA
300           Oracle          CA

I am looking to do something similar to .replace, however instead of replacing the value in column, I would like to replace the value in another column.

I know this is similar to a .replace method, but I'm having trouble having the key and values be in different columns. Any help would be very appreciated!!

Joel
  • 105
  • 6

1 Answers1

0

Use map with .fillna:

df['Company Name'] = df['Company ID'].map(dct).fillna(df['Company Name'])

   Company ID  Company Name State
0         100   Apple, Inc.    CA
1         100   Apple, Inc.    CA
2         200  Amazon, Inc.    WA
3         200  Amazon, Inc.    WA
4         300        Oracle    CA
5         300        Oracle    CA
Erfan
  • 40,971
  • 8
  • 66
  • 78