Home > Back-end >  Generate Last Day of Quarter from Quarter Number and Year
Generate Last Day of Quarter from Quarter Number and Year

Time:01-27

I have a pandas Data Frame containing column Quarter and Year. I want to create the column Date where date would be the last date of that quarter.

Create a dummy data frame using code below:

data = {'year':[2021, 2022, 2023, 2024],
        'quarter':[1, 2, 3, 4]}
df = pd.DataFrame(data)

Expected Output

 ------ --------- ------------ 
| year | quarter |    Date    |
 ------ --------- ------------ 
| 2021 |       1 | 2021-03-31 |
| 2022 |       2 | 2022-06-30 |
| 2023 |       3 | 2023-09-30 |
| 2024 |       4 | 2024-12-31 |
 ------ --------- ------------ 

CodePudding user response:

Use:

df['Date'] = (pd.PeriodIndex(df['year'].astype(str)   'Q'   df['quarter'].astype(str), 
                             freq='Q')
                .to_timestamp(how='e')
                .normalize())
print (df)
   year  quarter       Date
0  2021        1 2021-03-31
1  2022        2 2022-06-30
2  2023        3 2023-09-30
3  2024        4 2024-12-31
  •  Tags:  
  • Related