Home > Enterprise >  Map values in column with a dictionary
Map values in column with a dictionary

Time:01-09

I have two dataframes imported from files

df1 output(sample):

Country Currency Code
UNITED STATES US DOLLAR USD
PUERTO RICO US DOLLAR USD
UNITED KINGDOM UK POUND STERLING GBP
GUERNSEY UK POUND STERLING GBP
JAPAN JAPANESE YEN JPY

df2 output(sample):

index Original Currency
0 US DOLLAR
1 UK POUND STERLING
2 JAPANESE YEN
3 US DOLLAR
4 US DOLLAR
5 UK POUND STERLING

I have converted both columns from df1 to a dictionary using: di = dict(zip(df1['Currency'], df1['Code']))

Currently, I am trying to map the values from my dictionary to my second dataframe's 'Original Currency' column; however, the attempts I have made either result in NaN values or no change at all.

I have attempted using both .map() and .replace() with little success

With .map()

df2['Original Currency'] = df2['Original Currency'].map(di)

With .replace()

df2['Original Currency'] = df2['Original Currency'].replace(di)

&

df3 = df2.replace({"Original Currency": di})

CodePudding user response:

Your code should work. Try this:

df2['Original Currency'] = df2['Original Currency'].map(df1.set_index('Currency')['Code'])
print(df2)

# Output
  Original Currency
0               USD
1               GBP
2               JPY

If it doesn't work, maybe you have some trailing whitespaces.

CodePudding user response:

You can use apply

df2['Original Currency'] = df2['Original Currency'].apply(lambda i: di[i])
  • Related