I have a dataframe, df, that has a quarters column where I would like to add an additional increased quarters column adjacent to it (increased by 2)
Data
JavaScript
x
8
1
id date
2
a Q1 2022
3
a Q1 2022
4
a Q1 2022
5
a Q1 2022
6
b Q1 2022
7
b Q1 2022
8
Desired
JavaScript
1
8
1
id date new
2
a Q1 2022 Q3 2022
3
a Q1 2022 Q3 2022
4
a Q1 2022 Q3 2022
5
a Q1 2022 Q3 2022
6
b Q1 2022 Q3 2022
7
b Q1 2022 Q3 2022
8
Doing
JavaScript
1
2
1
df['new'] = df.index + 2
2
However this is not adding 2 consistently to the entire column I am still troubleshooting, any suggestion is appreciated
Advertisement
Answer
Reformat the strings in date
in such a way that the resulting date format is YearQuarter
so that it can be parsed into PeriodIndex
, now add 2
to this index and strftime
to convert back to orignal format
JavaScript
1
3
1
s = df['date'].str.replace(r'(S+) (S+)', r'21')
2
df['new'] = (pd.PeriodIndex(s, freq='Q') + 2).strftime('Q%q %Y')
3
JavaScript
1
8
1
id date new
2
0 a Q1 2022 Q3 2022
3
1 a Q1 2022 Q3 2022
4
2 a Q1 2022 Q3 2022
5
3 a Q1 2022 Q3 2022
6
4 b Q1 2022 Q3 2022
7
5 b Q1 2022 Q3 2022
8