我如何在 pandas 中使用 lambda 函数

How could I use this function inside pandas with lambda

我有问题。我有一个数据框,其中包含国家/地区的 ISO 代码。我想将这些 ISO 代码更改为国家/地区名称。但不幸的是,我不知道如何在 .apply(lambda x:) 函数中使用这些函数。

数据框

   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

有字典:

d ={
'DE': 'Germany'.
 ...
}

然后这样做:

df['country'] = df['country'].apply(lambda x: d[x['country']])

此处最适合使用的函数可能是 map,用于 'country' 列。伪代码如下:

country_map = dict(zip(country_ids, country_names))
df['country'] = df['country'].map(country_map)

其中 country_ids 和 country_names 是输入代码和所需输出国家/地区名称的列表或列。

我认为您应该使用 df.apply 而不是 df['country'].applycountry

中的给定值创建新函数
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)