Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter dataframe for past 4 quarters

I have a DataFrame with start date and end date as a column. Firstly I need create a new column using End Date which consists of yearquarter (2022Q4) which I did using below code:

df[‘Quarter’]=pd.PeriodIndex(d[‘End Date’],freq=’Q’)

Now I want to filter data for past 4 quarters using End Date, lets say curremtly its 2023Q1, so I want to filter so That I can get data for (2022Q1, 2022Q2, 2022Q3, 2022Q4).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I achieve this in python.

>Solution :

Use Serie.dt.to_period for quarters with generate actual quarter by Timestamp and Timestamp.to_period, last filter by boolean indexing with Series.between:

df = pd.DataFrame({'End Date':pd.date_range('2021-12-01', freq='25D', periods=20)})
    
df['Quarter'] = df['End Date'].dt.to_period('q')

now = pd.Timestamp.now().to_period('q')

out = df[df['Quarter'].between(now - 4, now - 1)]
print (out)
     End Date Quarter
2  2022-01-20  2022Q1
3  2022-02-14  2022Q1
4  2022-03-11  2022Q1
5  2022-04-05  2022Q2
6  2022-04-30  2022Q2
7  2022-05-25  2022Q2
8  2022-06-19  2022Q2
9  2022-07-14  2022Q3
10 2022-08-08  2022Q3
11 2022-09-02  2022Q3
12 2022-09-27  2022Q3
13 2022-10-22  2022Q4
14 2022-11-16  2022Q4
15 2022-12-11  2022Q4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading