如何用 pandas 中的字典键替换列值 [英] how to replace column values with dictionary keys in pandas

查看:62
本文介绍了如何用 pandas 中的字典键替换列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个df,

 A     B
 one   six
 two   seven
 three level
 five   one

和词典

my_dict={1:"one,two",2:"three,four"}

我想用my_dict keys()替换df.A

I want to replace df.A with my_dict keys()

我想要的输出是

 A     B
 1     six
 1     seven
 2     level
 five     one

我尝试了df.A.replace(my_dict,regex=True)但出了错

请帮忙,谢谢!

推荐答案

您需要dict理解才能首先将每个值分隔为键:

You need dict comprehension for separate each values to keys first:

my_dict={1:"one,two",2:"three,four"}
d = {k: oldk for oldk, oldv in my_dict.items() for k in oldv.split(',')}
print (d)
{'one': 1, 'three': 2, 'four': 2, 'two': 1}

df.A = df.A.replace(my_dict)

这篇关于如何用 pandas 中的字典键替换列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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