通过从不同的列中查找值,用字典中的键填充DataFrame列

2024-06-01 00:55:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,看起来像:

> Country                     Code
> 'Bolivia'                   NaN
> 'Bolivia, The Republic of'  NaN

我还有一本字典

> CountryCode = {'BOL':['Bolivia','Bolivia, The Republic of']}

如果其中一个值在字典中,我该如何在dataframe中使用相应的键继续填充呢

所需输出为

> Country                     Code
> 'Bolivia'                   'BOL'
> 'Bolivia, The Republic of'  'BOL'

谢谢你的帮助


Tags: ofthe数据dataframe字典codenancountry
3条回答

创建CountryCode^{}的反向字典,其中Country列:

new_countrycode = {v:key for key,value in CountryCode.items() for v in value}
df['Code'] = df['Country'].map(new_countrycode)

print(df)
                    Country Code
0                   Bolivia  BOL
1  Bolivia, The Republic of  BOL

print(new_countrycode)
{'Bolivia': 'BOL', 'Bolivia, The Republic of': 'BOL'}

使用.apply()

df["Code"] = df.Country.apply(lambda x: ''.join(i for i, j in CountryCode.items() if x in j))

输出:

                    Country Code
0                   Bolivia  BOL
1  Bolivia, The Republic of  BOL
df=pd.DataFrame({'Country':['Bolivia','Bolivia, The Republic of'],'code':[None,None]})

从键值代码字典创建数据帧

df_keyval=pd.DataFrame({'CountryCode':{'BOL':['Bolivia','Bolivia, The Republic of']}}).reset_index()

匹配国家并获取相应的密钥:

for idx,rows in df.iterrows():
    if rows['Country'] in df_keyval.CountryCode[0]:
        df['code']=df_keyval.index[0]

输出:

    Country                    code
0   Bolivia                     BOL
1   Bolivia, The Republic of    BOL

相关问题 更多 >