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 dataframe columns by mapping with a dictionary but keeping original if no match

Say I have the following data:

dfData = pd.DataFrame({
    'A1':['1','2'],
    'B1':['1','2'],
    'C1':['1','2'],
    'D1':['1','2']
    })
print(dfData)
A1 B1 C1 D1
0 1 1 1
1 2 2 2

And I set the following map:

dfMap = pd.DataFrame({
    'dfDataCol':['A1','B1','C1',''],
    'NewCol'   :['A2','B2','C2','D2']
    })
print(dfMap)
dfDataCol NewCol
A1 A2
B1 B2
C1 C2

I convert to a dictionary and map the names:

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

dict1 = dfMap.set_index('dfDataCol').to_dict()['NewCol']
dfData.columns = dfData.columns.map(dict1)

I get:

A2 B2 C2 NaN
0 1 1 1
1 2 2 2

How do I keep the original heading if there is no dictionary entry:

A2 B2 C2 D1
0 1 1 1
1 2 2 2

>Solution :

Try:

dfData = dfData.rename(columns=dict1)

print(dfData)

Prints:

  A2 B2 C2 D1
0  1  1  1  1
1  2  2  2  2
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