簡體   English   中英

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

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

假設我有以下簡單的 pandas DataFrame:

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

以及帶有country /地區列中值縮寫的字典:

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

我想將 DataFrame 的country列中的值更改為字典中的查找值。 結果將如下所示:

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

我試着用

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

但這給出了以下錯誤:

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

我了解為什么會發生此錯誤(代碼嘗試使用 hash 和 object 而不是列中的字符串值),但是有沒有辦法解決這個問題?

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

印刷:

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

您可以使用 pandas function replace()特別考慮這些場景。 小心不要將它與不帶字典的 python 內置.str.repace()混淆。

嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM