简体   繁体   English

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

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

Assume I have the following simple pandas DataFrame:假设我有以下简单的 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:以及带有country /地区列中值缩写的字典:

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.我想将 DataFrame 的country列中的值更改为字典中的查找值。 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?我了解为什么会发生此错误(代码尝试使用 hash 和 object 而不是列中的字符串值),但是有没有办法解决这个问题?

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

You can use pandas function replace() especially thought for these scenarios.您可以使用 pandas function replace()特别考虑这些场景。 Careful not to confuse it with python's built-in .str.repace() which doesn't take dictionaries.小心不要将它与不带字典的 python 内置.str.repace()混淆。

Try with:尝试:

df['country'] = df['country'].replace(abr)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据字典键和值替换熊猫数据框列值? - How to replace pandas dataframe column values based on dictionary key and values? 使用另一个DataFrame中的行的值查找并替换pandas.Dataframe中的列标题 - Lookup and replace column headings in a pandas.Dataframe with the values from rows in another DataFrame 如何根据另一个 dataframe 中的查找值替换 pandas dataframe 值? - How to replace pandas dataframe values based on lookup values in another dataframe? 用字典中的值替换 pandas dataframe 中的一行 - Replace a row in a pandas dataframe with values from dictionary 通过从另一个数据帧中查找来替换 Pandas 数据帧中的所有值 - Replace all values in pandas dataframe by lookup from another dataframe 使用Series查找表替换Pandas DataFrame列中的值 - Replace values in column of Pandas DataFrame using a Series lookup table 如何从字典中替换 dataframe 列中的特定值? - How to replace particular values in dataframe column from a dictionary? 给定熊猫数据框列,如果 X 是字典中的键,如何用字典中的值替换嵌套列表中的元素 X? - Given the pandas dataframe column, how to replace elements X in a nested list with the values in dictionary if X is a key in a dictionary? 如何用字典键替换数据框列值? - How to replace dataframe column values with dictionary keys? 如何用pandas中的字典键替换列值 - how to replace column values with dictionary keys in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM