Home > database >  Rename pandas column based on a dictionary only if the name is in the dictionary
Rename pandas column based on a dictionary only if the name is in the dictionary

Time:04-08

I want to rename the columns in my dataframe, using a the names in a dictionary, but in my case, the dictionaries I have don't represent al the column names, so I want to change only the ones I have in my dictionary. For example

       key1 key2 key3 key4
index
1      val1 val2 val3 val4
2      val5 val6 val7 val8
3      ...
4
5

And my dictionary is

{'key1': 'name1',
 'key2': 'name2',
 'key4': 'name4'
}

what I want to get is

       name1 name2 key3 name4
index
1      val1 val2 val3 val4
2      val5 val6 val7 val8
3      ...
4
5

so I am trying to do the same as this question, but mapping doesn't work because the keys that are not in my dict end as Nans in the column names. Does anyone know how to do this? T-T

CodePudding user response:

You could use dict.get in a list comprehension (note that I named the dictionary d here):

df.columns = [d.get(k,k) for k in df.columns]

Output:

      name1 name2  key3 name4
index                        
1      val1  val2  val3  val4
2      val5  val6  val7  val8
  • Related