讓它成為以下 Python Pandas DataFrame。
| ID | 地區 |
|---|---|
| 12 | 法蘭克福機場 |
| 99 | GER |
| 13 | ESP |
| 69 | 英國 |
| 17 | GER |
| 02 | GER |
使用下一個代碼:
dictionary = {'GER': 'Germany', 'FRA': 'France'}
df['region'] = df['region'].map(dictionary)
我得到以下結果:
| ID | 地區 |
|---|---|
| 12 | 法國 |
| 99 | 德國 |
| 13 | 鈉 |
| 69 | 鈉 |
| 17 | 德國 |
| 02 | 德國 |
我的想法是字典中沒有出現的值,保留它們以前的值。
| ID | 地區 |
|---|---|
| 12 | 法國 |
| 99 | 德國 |
| 13 | ESP |
| 69 | 英國 |
| 17 | 德國 |
| 02 | 德國 |
我怎么能這樣做?先感謝您。
uj5u.com熱心網友回復:
我想你想要的是:
df.replace({"region": dictionary})

uj5u.com熱心網友回復:
使用fillna(或combine_first):
df['region'] = df['region'].map(dictionary).fillna(df['region'])
或利用該get方法將值設定為默認值:
df['region'] = df['region'].map(lambda x: dictionary.get(x, x))
輸出:
ID region
0 12 France
1 99 Germany
2 13 ESP
3 69 UK
4 17 Germany
5 2 Germany
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473194.html
上一篇:從嵌套for回圈到字典理解?
下一篇:根據條件遞回地向嵌套字典添加鍵
