如何用pandas

时间:2018-02-27 11:58:57

标签: python pandas dataframe data-analysis

我有一个df,

 A     B
 one   six
 two   seven
 three level
 five   one

和dictioinary

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

我想用my_dict键()

替换df.A.

我想要的输出是,

 A     B
 1     six
 1     seven
 2     level
 five     one

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

请帮助,提前谢谢!

2 个答案:

答案 0 :(得分:1)

首先需要字典理解将每个值分别用于键:

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)

答案 1 :(得分:1)

以下是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