Issue
I have the following df and dict:
df = pd.DataFrame({'a':[1,2,3,4], 'x':[11,12,13,14]})
dict_ = {'new_a':['a','b','c'],'new_x':['x','y','z']}
I would like to check if column 'a'
and 'x'
exist in dict_ values, if so, rename them with their key values.
Desired output:
df = pd.DataFrame({'new_a':[1,2,3,4], 'new_x':[11,12,13,14]})
Solution
Invert/flatten the dictionary and rename
:
d2 = {k:v for v,l in dict_.items() for k in l}
# {'a': 'new_a', 'b': 'new_a', 'c': 'new_a',
# 'x': 'new_x', 'y': 'new_x', 'z': 'new_x'}
out = df.rename(columns=d2)
output:
new_a new_x
0 1 11
1 2 12
2 3 13
3 4 14
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.