如何用字典中的查找值替换 pandas DataFrame 列?

Pet*_*ter 8 python dictionary dataframe pandas

假设我有以下简单的 pandas DataFrame:

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

以及包含列中值缩写的字典country

abr = {"Netherlands": "NL",
       "Germany": "GE",
       "United_States": "US",
       "England": "EN",
       "Canada": "CA"
}
Run Code Online (Sandbox Code Playgroud)

country我想将DataFrame 列中的值更改为字典中的查找值。结果如下:

    id  country
0   1   NE
1   2   GE
2   3   US
3   4   EN
4   5   CA
Run Code Online (Sandbox Code Playgroud)

我尝试使用

df["country"] = abr[df["country"]]
Run Code Online (Sandbox Code Playgroud)

但这给出了以下错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed
Run Code Online (Sandbox Code Playgroud)

我理解为什么会发生此错误(代码尝试对对象而不是列中的字符串值进行哈希处理),但是有没有办法解决这个问题?

Iva*_*sky 13

您可以使用replace()专为这些场景而设计的 pandas 函数。小心不要将它与 python 的内置函数混淆,str.replace()后者不使用字典。

尝试使用:

df['country'] = df['country'].replace(abr)
Run Code Online (Sandbox Code Playgroud)


And*_*ely 5

df["country"] = df["country"].map(abr)
print(df)
Run Code Online (Sandbox Code Playgroud)

印刷:

   id country
0   1      NL
1   2      GE
2   3      US
3   4      EN
4   5      CA
Run Code Online (Sandbox Code Playgroud)