Reputation: 197
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 :)
Upvotes: 2
Views: 2969
Reputation: 402633
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
Upvotes: 5