将pandas Dataframe列映射到字典值 [英] map pandas Dataframe columns to dictionary values
本文介绍了将pandas Dataframe列映射到字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个one:man字典.我想将pandas Dataframe列的值映射到字典的键(非值).这是我的字典:
I have a one:many dictionary. I would like to map the values of a pandas Dataframe column to the keys (NOT values) of the dictionary. here is my dictionary:
dict1={'fruits':('apple','grapes','oranges'),'food':('fish','meat','fibre')}
这是pandas系列对象:
And here is the pandas Series object:
df=pd.Series(['fish','apple','meat'])
我想要的期望输出:
0 food
1 fruits
2 food
dtype: object
推荐答案
如果其他"同时存在于水果"和食物"中怎么办?这就是为什么如果没有某种逻辑来解决重复项就无法进行反向查找的原因.
What if 'other' was in both 'fruits' and 'food'? That is why you cannot do a reverse lookup without having some sort of logic to resolve duplicates.
如果您的值都是唯一的,则可以使用字典理解来反转字典:
If your values are all unique, then you can reverse your dictionary using a dictionary comprehension:
reversed_dict = {val: key for key in dict1 for val in dict1[key]}
>>> reversed_dict
{'apple': 'fruits',
'fibre': 'food',
'fish': 'food',
'grapes': 'fruits',
'meat': 'food',
'oranges': 'fruits'}
然后可以进行映射.
>>> pd.Series(['fish','apple','meat']).map(reversed_dict)
0 food
1 fruits
2 food
dtype: object
这篇关于将pandas Dataframe列映射到字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文