pandas 写入字典_将pandas Dataframe列映射到字典值

本文介绍如何将pandas DataFrame的一列值映射到字典的键。提供了一个例子,展示了如何处理可能出现的重复值问题,并给出了当字典值唯一时反转字典的方法,以实现所需映射。
摘要由CSDN通过智能技术生成

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')}

And here is the pandas Series object:

df=pd.Series(['fish','apple','meat'])

the desired output i want:

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'}

You could then map.

>>> pd.Series(['fish','apple','meat']).map(reversed_dict)

0 food

1 fruits

2 food

dtype: object

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值