[英]How could I use this function inside pandas with lambda
我有个问题。 我有一个 dataframe,其中包含国家/地区的 ISO 代码。 我想将这些 ISO 代码更改为国家/地区名称。 但不幸的是,我不知道如何在.apply(lambda x:)
function 中使用这些函数。
Dataframe
id country
0 1 DE
1 2 DE
2 3 CN
3 4 BG
4 3 CN
5 4 BG
6 5 BG
代码
import pandas as pd
import pycountry
input_countries = ['BG', 'CN', 'DE']
countries = {}
for country in pycountry.countries:
countries[country.alpha_2] = country.name
codes = [countries.get(country, 'Unknown code') for country in input_countries]
import pandas as pd
d = {'id': [1, 2, 3, 4, 3, 4, 5], 'country': ['DE', 'DE', 'CN', 'BG', 'CN', 'BG', 'BG']}
df = pd.DataFrame(data=d)
# print(df)
df['country'] = df['country'].apply(lambda x: ...)
我想要的是
id country
0 1 Germany
1 2 Germany
2 3 China
3 4 Bulgaria
4 3 China
5 4 Bulgaria
6 5 Bulgaria
最适合在这里使用的 function 可能是map
,用于“国家/地区”列。 伪代码如下:
country_map = dict(zip(country_ids, country_names))
df['country'] = df['country'].map(country_map)
其中 country_ids 和 country_names 是输入代码的列表或列以及所需的 output 国家/地区名称。
我认为您应该使用df.apply
而不是df['country'].apply
从country
列中的给定值创建新的 function
import pandas as pd
import pycountry
input_countries = ['BG', 'CN', 'DE']
countries = {}
for country in pycountry.countries:
countries[country.alpha_2] = country.name
codes = [countries.get(country, 'Unknown code') for country in input_countries]
import pandas as pd
d = {'id': [1, 2, 3, 4, 3, 4, 5], 'country': ['DE', 'DE', 'CN', 'BG', 'CN', 'BG', 'BG']}
df = pd.DataFrame(data=d)
# print(df)
df['country'] = df.apply(lambda x: countries[x['country']], axis=1)
有字典:
d ={
'DE': 'Germany'.
...
}
然后这样做:
df['country'] = df['country'].apply(lambda x: d[x['country']])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.