2 回答
TA贡献1805条经验 获得超9个赞
默认情况下,您可以通过原始 DataFrame创建辅助 DataFrameDataFrame.from_dict和DataFrame.join到原始 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)
TA贡献1810条经验 获得超4个赞
可以通过以下方式实现相同的目标map:
df.join(pd.DataFrame(df['cntr'].map(m).tolist(), columns=['name', 'region']))
输出:
cntr name region
0 CN China Asia
1 CH Switzerland Europe
添加回答
举报