我有一个国家/地区代码df:
cntr
0 CN
1 CH
我想映射字典中的全名和地区
cntrmap = {"CN":["China","Asia"],"CH":["Switzerland","Europe"]}
我原本希望这样,但是不起作用。
df['name'] = df['cntr'].map(cntrmap)[0]
df['region'] = df['cntr'].map(cntrmap)[1]
你们有什么建议吗? 谢谢大家!
答案 0 :(得分:1)
默认情况下,您可以通过DataFrame.from_dict
和DataFrame.join
创建助手DataFrame到原始DataFrame的默认左连接:
df = pd.DataFrame({'cntr':['CN','CH']})
cntrmap = {"CN":["China","Asia"],"CH":["Switzerland","Europe"]}
df1 = pd.DataFrame.from_dict(cntrmap, orient='index', columns=['name','region'])
df = df.join(df1, on='cntr')
print (df)
cntr name region
0 CN China Asia
1 CH Switzerland Europe
如果为map
创建2个字典,您的解决方案将起作用:
map1 = {k:v[0] for k, v in cntrmap.items()}
map2 = {k:v[1] for k, v in cntrmap.items()}
df['name'] = df['cntr'].map(map1)
df['region'] = df['cntr'].map(map2)
答案 1 :(得分:1)
使用map
可以达到相同的目的:
df.join(pd.DataFrame(df['cntr'].map(m).tolist(), columns=['name', 'region']))
输出:
cntr name region
0 CN China Asia
1 CH Switzerland Europe