Yash Ghorpade
Yash Ghorpade

Reputation: 607

How to Convert dates into Quarter in Python Pandas without repeating quarters for preceding 5 years?

I want to convert Date into Quarters. I've used,

x['quarter'] = x['date'].dt.quarter

        date    quarter
0   2013-1-1          1

But, it also repeats the same for the next year.

          date    quarter
366   2014-1-1          1

Instead of the 1, I want the (expected result) quarter to be 5.

          date    quarter
366   2014-1-1          5
.
.
.
.
          date    quarter
731   2015-1-1          9

Upvotes: 1

Views: 78

Answers (1)

rafaelc
rafaelc

Reputation: 59274

You can use a simple mathematical operation

starting_year = 2013
df['quarter'] = df.year.dt.quarter + (df.year.dt.year - starting_year)*4

    year        quarter
0   2013-01-01  1
0   2014-01-01  5
0   2015-01-01  9
0   2016-01-01  13

Upvotes: 1

Related Questions