I have a df,
A B
one six
two seven
three level
five one
and a dictionary
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 it doesn't work.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With