将pandas Dataframe列映射到字典值

Sir*_* S. 7 python dictionary dataframe pandas

我有一个:很多字典.我想将pandas Dataframe列的值映射到字典的键(NOT值).这是我的字典:

dict1={'fruits':('apple','grapes','oranges'),'food':('fish','meat','fibre')}
Run Code Online (Sandbox Code Playgroud)

这里是熊猫系列对象:

df=pd.Series(['fish','apple','meat'])
Run Code Online (Sandbox Code Playgroud)

我想要的所需输出:

0      food
1    fruits
2      food
dtype: object
Run Code Online (Sandbox Code Playgroud)

Ale*_*der 7

如果"其他"同时出现在"水果"和"食物"中会怎样?这就是为什么在没有某种逻辑来解决重复的情况下你不能进行反向查找的原因.

如果您的值都是唯一的,那么您可以使用字典理解来反转字典:

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'}
Run Code Online (Sandbox Code Playgroud)

然后你可以映射.

>>> pd.Series(['fish','apple','meat']).map(reversed_dict)
0      food
1    fruits
2      food
dtype: object
Run Code Online (Sandbox Code Playgroud)