将具有多个键的Python字典映射到具有多个与键匹配的列的数据框中 [英] Mapping Python dictionary with multiple keys into dataframe with multiple columns matching keys

查看:110
本文介绍了将具有多个键的Python字典映射到具有多个与键匹配的列的数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,希望将其映射到当前数据框并创建一个新列。我在元组中有键,它们映射到数据框中的两个不同列。

I have a dictionary that I would like to map onto a current dataframe and create a new column. I have keys in a tuple, which map onto two different columns in my dataframe.

dict = {('County', 'State'):'CountyType'}
df = pd.DataFrame(data=['County','State'])

我想使用 dict 创建一个新列 CountyType 放在 df 的两列中。但是,执行以下操作给我一个错误。

I would like to create a new column, CountyType, using dict to map onto the two columns in df. However, doing the following gives me an error. How else could this be done?

df['CountyType'] = (list(zip(df.County,df.State)))
df = df.replace({'CountyType': county_type_dict)


推荐答案

您可以从两个系列中创建一个 MultiIndex ,然后进行映射。来自@ALollz的数据。

You can create a MultiIndex from two series and then map. Data from @ALollz.

df['CountyType'] = df.set_index(['County', 'State']).index.map(dct.get)

print(df)

  County  State CountyType
0      A      1        One
1      A      2       None
2      B      1       None
3      B      2        Two
4      B      3      Three

这篇关于将具有多个键的Python字典映射到具有多个与键匹配的列的数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆