ah bon
ah bon

Reputation: 10021

Create a range of quarters from year to year in Python

I wish to create a list of all the quarters from a given range of years, say from 2018 to 2020, ie.: [2018-q1, 2018-q2, ..., 2020-q4].

How could I achieve that in Pandas?

This code may be useful: pd.PeriodIndex(df.date, freq='Q')

Upvotes: 1

Views: 1289

Answers (2)

Anurag Dabas
Anurag Dabas

Reputation: 24314

use pd.PeriodIndex()+pd.date_range():

out = pd.PeriodIndex(pd.date_range('2018-01-01','2021-01-01',freq = 'Q'), freq = 'Q')
print(out)

Out:

PeriodIndex(['2018Q1', '2018Q2', '2018Q3', '2018Q4', '2019Q1', '2019Q2',
             '2019Q3', '2019Q4', '2020Q1', '2020Q2', '2020Q3', '2020Q4'],
            dtype='period[Q-DEC]')

OR

pd.date_range()+to_period():

out = pd.date_range('2018-01-01', '2021-01-01', freq = 'Q').to_period('Q')
print(out)

Out:

PeriodIndex(['2018Q1', '2018Q2', '2018Q3', '2018Q4', '2019Q1', '2019Q2',
             '2019Q3', '2019Q4', '2020Q1', '2020Q2', '2020Q3', '2020Q4'],
            dtype='period[Q-DEC]')

Upvotes: 4

lionking-123
lionking-123

Reputation: 311

Glad to answer on your question.

idx = pd.Series(pd.period_range(start="2018-Q1", end="2020-Q4", freq="Q")).array
print(idx)

Out:

['2018Q1', '2018Q2', '2018Q3', '2018Q4', '2019Q1', '2019Q2', '2019Q3',
 '2019Q4', '2020Q1', '2020Q2', '2020Q3', '2020Q4']
Length: 12, dtype: period[Q-DEC]

Hope to be helpful for you. Thanks.

Upvotes: 1

Related Questions