【发布时间】:2022-06-19 02:14:32
【问题描述】:
我的数据如下:
import pandas as pd
import country_converter as coco
cc = coco.CountryConverter()
example = pd.DataFrame.from_dict({'Country': {0: 'Fiji', 1: 'Tanzania', 2: 'W. Sahara', 3: 'Canada', 4: 'United States of America', 5: 'Kazakhstan', 6: 'Uzbekistan', 7: 'Papua New Guinea', 8: 'Indonesia', 9: 'Argentina', 10: 'Chile', 11: 'Dem. Rep. Congo', 12: 'Somalia', 13: 'Kenya', 14: 'Sudan', 15: 'Chad', 16: 'Haiti', 17: 'Dominican Rep.', 18: 'Russia', 19: 'Bahamas', 20: 'Falkland Is.', 21: 'Norway'}, 'iso': {0: 'FJI', 1: 'TZA', 2: 'ESH', 3: 'CAN', 4: 'USA', 5: 'KAZ', 6: 'UZB', 7: 'PNG', 8: 'IDN', 9: 'ARG', 10: 'CHL', 11: 'COD', 12: 'SOM', 13: 'KEN', 14: 'SDN', 15: 'TCD', 16: 'HTI', 17: 'DOM', 18: 'RUS', 19: 'BHS', 20: 'FLK', 21: '-99'}}
)
Country iso
0 Fiji FJI
1 Tanzania TZA
2 W. Sahara ESH
3 Canada CAN
4 United States of America USA
5 Kazakhstan KAZ
6 Uzbekistan UZB
7 Papua New Guinea PNG
8 Indonesia IDN
9 Argentina ARG
10 Chile CHL
11 Dem. Rep. Congo COD
12 Somalia SOM
13 Kenya KEN
14 Sudan SDN
15 Chad TCD
16 Haiti HTI
17 Dominican Rep. DOM
18 Russia RUS
19 Bahamas BHS
20 Falkland Is. FLK
21 Norway -99
我希望 python 尝试:
example['iso'] = cc.convert(names = example['Country'], to = 'ISO3')
但仅如果iso=-99的值
我看到this solution,所以我尝试了:
example = example.assign(col = [(cc.convert(names = example['Country'], to = 'ISO3')) if iso = '-99' else (example['iso']) for iso in example['iso']])
但这不是正确的语法。
有人可以帮帮我吗?
【问题讨论】:
-
example.loc[example['iso'] == '-99', 'iso'] = 'ISO3'? -
定义一个小函数,试试
apply方法 -
感谢您的评论。但结果应该是函数的评估,而不是特定的字符串。我可以用函数替换字符串吗?