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

这篇博客介绍了如何将Pandas DataFrame中的一列值映射到一个字典的键,从而得到一个新的Series。当字典的键可能有重复值时,解决这个问题的方法是创建一个反向字典,通过字典推导式完成。然后使用这个反向字典进行映射操作,得到期望的输出。
摘要由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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值