Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename df column name with dictionary key in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading