Pandas | period_range method
Start your free 7-days trial now!
Pandas period_range(~)
method returns a PeriodIndex
with fixed frequency. A Period
represents a specific time span or a duration. PeriodIndex
is most often used as the index of a DataFrame.
Parameters
1. start
link | string
or period-like
| optional
The lower bound (inclusive) of the range. By default, start=None
.
2. end
link | string
or period-like
| optional
The upper bound (inclusive) of the range. By default, end=None
.
3. periods
link | int
| optional
The desired number of periods. By default, periods=None
.
Out of the above three parameters, exactly two must be specified - no less, no more.
4. freq
link | string
or DateOffset
| optional
The step-size (interval size) between a pair of consecutive dates. By default, freq="D"
(step-size of a day).
5. name
link | string
| optional
The name to assign to the resulting PeriodIndex
. By default, name=None
.
Return Value
A PeriodIndex
.
Examples
Basic usage
To create a sequence of dates from 2020-12-25
to 2020-12-27
(both inclusive):
pd.period_range(start="2020-12-25", end="2020-12-27")
PeriodIndex(['2020-12-25', '2020-12-26', '2020-12-27'], dtype='period[D]', freq='D')
The default step-size (the frequency) is a day, so this is why we see freq="D"
in the output.
Specifying the period
To create a sequence of dates of length 3
from 2020-12-25
(inclusive):
pd.period_range(start="2020-12-25", periods=3)
PeriodIndex(['2020-12-25', '2020-12-26', '2020-12-27'], dtype='period[D]', freq='D')
Specifying the frequency
In Pandas, frequency can be thought of as the length of a period. The default frequency is 1 day.
Let's try a 2-day interval:
pd.period_range(start="2020-12-25", periods=3, freq="2D")
PeriodIndex(['2020-12-25', '2020-12-27', '2020-12-29'], dtype='period[2D]', freq='2D')
Notice how we have our specified freq="2D"
encoded into the resulting PeriodIndex
.
Let's now try a 1-month interval:
pd.period_range(start="2020-12-25", periods=3, freq="M")
PeriodIndex(['2020-12', '2021-01', '2021-02'], dtype='period[M]', freq='M')
Note that we could have also used freq="1M"
for the same effect.
Specifying a name
To give a name to the resulting PeriodIndex
:
pd.period_range(start="2020-12-25", periods=3, name="My Dates")
PeriodIndex(['2020-12-25', '2020-12-26', '2020-12-27'], dtype='period[D]', name='My Dates', freq='D')
Notice how we have name="My Dates"
encoded into the PeriodIndex
.
Using PeriodIndex as the index of a DataFrame
To initialise a DataFrame with PeriodIndex
:
idx = pd.period_range(start="2020-12-25", periods=3)
A2020-12-25 a2020-12-26 b2020-12-27 c