how to replace column values with dictionary keys in pandas

霸气de小男生 提交于 2019-12-24 07:27:45

问题


I hava a df,

 A     B
 one   six
 two   seven
 three level
 five   one

and a dictioinary

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

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

my desired output is,

 A     B
 1     six
 1     seven
 2     level
 five     one

I tried df.A.replace(my_dict,regex=True) but goes wrong

pls help, thanks in advance!


回答1:


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)



回答2:


Here is one solution via map / fillna:

d = {v_i: k for k, v in my_dict.items() for v_i in v.split(',')}
df['A'] = df['A'].map(d).fillna(df['A'])

#       A      B
# 0     1    six
# 1     1  seven
# 2     2  level
# 3  five    one


来源:https://stackoverflow.com/questions/49008179/how-to-replace-column-values-with-dictionary-keys-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!