首页 > 解决方案 > 尝试基于两列值和一个有异常的字典创建新列

问题描述

我正在尝试获取国家/地区键,然后从中填充国家/地区列。但是,我有一本包含期望的字典。

excpt_dict = dict(zip(df_cc_ex['VendorAcct'], df_cc_ex['ASO Country'])) #Creates dict of exceptions
df['Country'] = df['CountryKey'].map(country_dict) #Creates new column translating country key into country
df.loc[(df['VendorAccount'] in excpt_dict.keys()), ('Country')] = excpt_dict.values() #Changes new column according to exception

Sample Data
df
VendorAccount, CountryKey
000000       , US        
000001       , MX       
000002       , US       

df after mapping country dict
VendorAccount, CountryKey, Country
000000       , US        , United States
000001       , MX        , Mexico
000002       , US        , United States

Excpt_dict = {000002:'Mexico'}

hopeful solution after using the excpt_dict
df
VendorAccount, CountryKey, Country
000000       , US        , United States
000001       , MX        , Mexico
000002       , US        , Mexico

我的意图是首先创建这个新列“国家”,然后使用字典查找例外的特定 ID 号,然后根据字典更改国家值。我希望得到一些建议

-- 编辑显示样本数据和有希望的解决方案

标签: pythondataframe

解决方案


推荐阅读