簡體   English   中英

我怎么能在 pandas 和 lambda 中使用這個 function

[英]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'].applycountry列中的給定值創建新的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM