Home > Software design >  Rename df column name with dictionary key in Python
Rename df column name with dictionary key in Python

Time:10-26

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]})

CodePudding user response:

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
  • Related