[英]How could I use this function inside pandas with lambda
I have a problem.我有个问题。 I have a dataframe, that contains ISO-codes of countries.
我有一个 dataframe,其中包含国家/地区的 ISO 代码。 I want to change these ISO-codes to country names.
我想将这些 ISO 代码更改为国家/地区名称。 But unfortunately I do not know how I could use these functions inside a
.apply(lambda x:)
function.但不幸的是,我不知道如何在
.apply(lambda x:)
function 中使用这些函数。
Dataframe Dataframe
id country
0 1 DE
1 2 DE
2 3 CN
3 4 BG
4 3 CN
5 4 BG
6 5 BG
Code代码
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: ...)
What I want我想要的是
id country
0 1 Germany
1 2 Germany
2 3 China
3 4 Bulgaria
4 3 China
5 4 Bulgaria
6 5 Bulgaria
The most suitable function to use here is probably map
instead, for the 'country' column.最适合在这里使用的 function 可能是
map
,用于“国家/地区”列。 Pseudo code as below:伪代码如下:
country_map = dict(zip(country_ids, country_names))
df['country'] = df['country'].map(country_map)
where country_ids and country_names are the lists or columns of the input codes and the desired output country names.其中 country_ids 和 country_names 是输入代码的列表或列以及所需的 output 国家/地区名称。
I think you should use df.apply
instead of df['country'].apply
to create new function from the given value in country
column我认为您应该使用
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)
Have a dictionary:有字典:
d ={
'DE': 'Germany'.
...
}
Then do this:然后这样做:
df['country'] = df['country'].apply(lambda x: d[x['country']])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.