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:
JavaScript
x
2
1
d.rename(columns = lambda x: 'FY1920' if x.endswith('2019') else x)
2
also tried:
JavaScript
1
3
1
d.columns.str.contains('2019')
2
d.rename(lambda x:'FY1920' if any(k in x for k in keys) else x, axis=1)
3
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:
JavaScript
1
7
1
df = pd.DataFrame('x', index=[0, 1], columns=['1/1/2019', '1/1/2020'])
2
df
3
4
1/1/2019 1/1/2020
5
0 x x
6
1 x x
7
JavaScript
1
7
1
df2 = df.rename(columns=lambda c: 'FY1920' if c.endswith('2019') else c)
2
df2
3
4
FY1920 1/1/2020
5
0 x x
6
1 x x
7
Another option is to use set_axis
or direct assignment:
JavaScript
1
13
13
1
df.set_axis(
2
labels=['FY1920' if c.endswith('2019') else c for c in df],
3
axis=1,
4
inplace=True)
5
# or
6
# df.columns = ['FY1920' if c.endswith('2019') else c for c in df]
7
8
df
9
10
FY1920 1/1/2020
11
0 x x
12
1 x x
13