How to replace a pandas DataFrame column with lookup values from a dictionary?

Viewed 1760

Assume I have the following simple pandas DataFrame:

df = pd.DataFrame({"id": [1, 2, 3, 4, 5],
                   "country": ["Netherlands", "Germany", "United_States", "England", "Canada"]})

and a dictionary with abbreviations for the values in the country column:

abr = {"Netherlands": "NL",
       "Germany": "GE",
       "United_States": "US",
       "England": "EN",
       "Canada": "CA"
}

I want to change the values in the country column of the DataFrame to the lookup values in the dictionary. The result would look like this:

    id  country
0   1   NE
1   2   GE
2   3   US
3   4   EN
4   5   CA

I tried to do it using

df["country"] = abr[df["country"]]

but that gives the following error:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

I understand why this error happens (the code tries to hash an object instead of the string value in the column), but is there a way to solve this?

2 Answers

You can use pandas function replace() especially thought for these scenarios. Careful not to confuse it with python's built-in .str.repace() which doesn't take dictionaries.

Try with:

df['country'] = df['country'].replace(abr)
df["country"] = df["country"].map(abr)
print(df)

Prints:

   id country
0   1      NL
1   2      GE
2   3      US
3   4      EN
4   5      CA
Related