I am trying to generate a 4-4-5 calendar. I have a dataframe of dates from 29-03-2020 to 2022-04-09 consisting of their equivalent week number. 29-03-2020 is the starting date of the fiscal year. I am trying to generate a column with their respective quarters it would belong to.
Here is the final df I am looking for,
a | count | quarter
2020-04-04 | 1 | Q1 2021
2020-04-11 | 2 | Q1 2021
.
.
.
2021-03-27 | 52 | Q4 2021
2021-04-03 | 53 | Q4 2021 #since 2020 is a leap year there are 53 weeks otherwise it will be 52 weeks
2021-04-10 | 1 | Q1 2022
2021-04-17 | 2 | Q1 2022
.
2022-03-02 | 52 | Q4 2022
2022-04-09 | 1 | Q1 2023
I made the following attempt,
import pandas as pd
import numpy as np
year_start = '2020-03-29'
year_end = '2022-04-09'
week_end_sat = pd.DataFrame(pd.date_range(year_start, year_end, freq=f'W-SAT'), columns=['a'])
first_day_of_year = week_end_sat.iloc[0, 0].replace(day=1, month=1)
baseline = pd.DataFrame(pd.date_range(first_day_of_year, periods=len(week_end_sat), freq=f'W-SAT'), columns=['a'])
week_end_sat['count'] = baseline['a'].dt.isocalendar().week
week_end_sat['quarter'] = 'Q' + baseline['a'].dt.quarter.astype(str) + ' ' + (baseline['a'].dt.year+1).astype(str)
week_end_sat['b'] = baseline['a']
all_days_df = pd.DataFrame(pd.date_range(year_start, year_end), columns=['a'])
merge_df = pd.merge(all_days_df,week_end_sat, on='a', how='left')
merge_df['count'] = merge_df['count'].bfill()
merge_df['quarter'] = merge_df['quarter'].bfill()
merge_df['week_day'] = merge_df['a'].dt.day_name()
I get the quarters correct till week number 52, that is, Q4 2021 but after that it messes up. For 53rd week I get Q1 2022 and so on. Shouldn't it be Q4 2021 for 53rd week as well since it is a leap year? Could anyone guide me as to I may correct this?
EDIT
What if I also want to display the Month it belongs to for each date?
The final df should look like this,
a | count | quarter | month
2020-04-04 | 1 | Q1 2021 | 2020-04
2020-04-11 | 2 | Q1 2021 | 2020-04
.
.
.
2021-03-27 | 52 | Q4 2021 | 2021-03
2021-04-03 | 53 | Q4 2021 | 2021-03
2021-04-10 | 1 | Q1 2022 | 2021-04
2021-04-17 | 2 | Q1 2022 | 2021-04
.
2022-03-02 | 52 | Q4 2022 | 2022-03
2022-04-09 | 1 | Q1 2023 | 2022-04