Home > Software design >  Rename dataframe columns by mapping with a dictionary but keeping original if no match
Rename dataframe columns by mapping with a dictionary but keeping original if no match

Time:09-19

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:

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

CodePudding user response:

Try:

dfData = dfData.rename(columns=dict1)

print(dfData)

Prints:

  A2 B2 C2 D1
0  1  1  1  1
1  2  2  2  2
  • Related