如何用字典键替换列值

Vic*_*cky 4 python data-analysis dataframe pandas

我有一个 df,

 A     B
 one   six
 two   seven
 three level
 five  one
Run Code Online (Sandbox Code Playgroud)

和一本字典

my_dict={1:"one,two",2:"three,four"}
Run Code Online (Sandbox Code Playgroud)

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

我想要的输出是,

 A     B
 1     six
 1     seven
 2     level
 five  one
Run Code Online (Sandbox Code Playgroud)

我尝试过df.A.replace(my_dict,regex=True),但没有成功。

jez*_*ael 5

您需要字典理解才能首先将每个值与键分开:

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)
Run Code Online (Sandbox Code Playgroud)