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

convert yyyyqq to pandas date in clean way

I am trying to convert year and quarter to date in pandas. In example below I am trying to get 1980-03-31 for 1980Q1 and so on.

df=pd.DataFrame({'year':['1980','1980','1980','1980'],'qtr':
                 ['Q1','Q2','Q3','Q4']})

scenario['date']=pd.to_datetime(scenario['year']+scenario['qtr'], infer_datetime_format=True)
scenario[['date','year','qtr']]
      date      year    qtr
0   1980-01-01  1980    Q1
1   1980-04-01  1980    Q2
2   1980-07-01  1980    Q3
3   1980-10-01  1980    Q4

>Solution :

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

are you looking for QuarterEnd offset?

import pandas as pd

df=pd.DataFrame({'year':['1980','1980','1980','1980'],'qtr':
                 ['Q1','Q2','Q3','Q4']})

df['date'] = pd.to_datetime(df['year']+df['qtr']) + pd.tseries.offsets.QuarterEnd()

df[['date','year','qtr']]
        date  year qtr
0 1980-03-31  1980  Q1
1 1980-06-30  1980  Q2
2 1980-09-30  1980  Q3
3 1980-12-31  1980  Q4
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