Skip to content
Advertisement

Rename column containing substring – Pandas

I need to rename columns in containing specific substring. In my case I am using data with columns that are named a specific date dd/mm/yyyy. I want to rename the column based on the yyyy of the column name (eg. 30/06/2020 rename FY1920).

Approach I have tried is as follows:

d.rename(columns = lambda x: 'FY1920' if x.endswith('2019') else x)

also tried:

d.columns.str.contains('2019')
d.rename(lambda x:'FY1920' if any(k in x for k in keys) else x, axis=1)

I am sure there is an easy way. Any ideas?

Thanks :)

Advertisement

Answer

rename does not work in-place, you need to assign the result back:

df = pd.DataFrame('x', index=[0, 1], columns=['1/1/2019', '1/1/2020'])
df

  1/1/2019 1/1/2020
0        x        x
1        x        x
df2 = df.rename(columns=lambda c: 'FY1920' if c.endswith('2019') else c)
df2
 
  FY1920 1/1/2020
0      x        x
1      x        x 

Another option is to use set_axis or direct assignment:

df.set_axis(
    labels=['FY1920' if c.endswith('2019') else c for c in df], 
    axis=1, 
    inplace=True)
# or 
# df.columns = ['FY1920' if c.endswith('2019') else c for c in df]

df

  FY1920 1/1/2020
0      x        x
1      x        x
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement