Stemming_from_jem Stemming_from_jem - 3 months ago 9
Python Question

Bulk rename of Pandas DF columns using 'try'

I have a data set that has variable column names. I would like to rename the columns it using

df.rename(columns={})
command.

Since some columns don't always appear in the DF I often raise exceptions. Is there a way to couple
try
with the rename command?

ie something like this:

df=df.rename(columns={try: 'a':'alpha','b':'beta' })

Answer

rename() will ignore not existing columns:

Demo:

In [11]: df
Out[11]:
   a  b  c
0  2  2  9
1  3  5  5
2  0  8  0
3  9  8  1
4  2  2  3

In [12]: df.rename(columns={'a':'AA','b':'BB','z':'ZZ'})
Out[12]:
   AA  BB  c
0   2   2  9
1   3   5  5
2   0   8  0
3   9   8  1
4   2   2  3