-2

I have a data frame:

    ID    Date     Volume 
    1    2019Q1      9
    1    2020Q2     11
    2    2019Q3     39
    2    2020Q4     23

I want to convert this to yyyy-Qn to datetime.

I have used a dictionary to map the corresponding dates to the quarters.

But I need a more generalized code in instances where the yyyy changes.

Expected output:

     ID    Date     Volume 
     1    2019-03     9
     1    2020-06    11
     2    2019-09    39
     2    2020-12    23
accdias
  • 5,160
  • 3
  • 19
  • 31
tj judge
  • 626
  • 3
  • 17

2 Answers2

2

Here's a simple solution but not as efficient (shouldn't be a problem if your dataset is not too large).

Convert the date column to datetime using to_datetime. Then add 2 months to each date because you want month to be end-of-quarter month

df = pd.DataFrame({'date': ["2019Q1" ,"2019Q3", "2019Q2", "2020Q4"], 'volume': [1,2,3, 4]})
df['datetime'] = pd.to_datetime(df['date'])
df['datetime'] = df['datetime'] + pd.DateOffset(months=2)

Output is the same

date    volume  datetime
0   2019Q1  1   2019-03-01
1   2019Q3  2   2019-09-01
2   2019Q2  3   2019-06-01
3   2020Q4  4   2020-12-01
Shubham Periwal
  • 2,198
  • 2
  • 8
  • 26
2

Let's use pd.PeriodIndex:

df['Date_new'] = pd.PeriodIndex(df['Date'], freq='Q').strftime('%Y-%m')

Output:

   ID    Date  Volume Date_new
0   1  2019Q1       9  2019-03
1   1  2020Q2      11  2020-06
2   2  2019Q3      39  2019-09
3   2  2020Q4      23  2020-12
Scott Boston
  • 147,308
  • 15
  • 139
  • 187