Pandas | PeriodIndex constructor
Start your free 7-days trial now!
Pandas PeriodIndex(~)
constructor creates a new PeriodIndex
object, which represents a specific time span or a duration. PeriodIndex
is most often used as the index of a DataFrame.
The difference between PeriodIndex
and DatetimeIndex
is as follows:
PeriodIndex
represents a time span with a precise start and end time.DatetimeIndex
represents a specific point in time.
Instead of calling this constructor directly, opt to use period_range(~)
instead, which is more flexible and widely used.
Parameters
1. data
| array-like
| optional
An array-like containing the dates to construct the PeriodIndex
.
2. copy
| boolean
| optional
If
True
, then a new copy ofdata
will be returned - modifying this copied data will not mutate the originaldata
, and vice versa.If
False
, then the returned PeriodIndex will use the same memory block asdata
. This means that modifying the return value will mutate the originaldata
, and vice versa.
By default, copy=False
.
3. freq
link | string
or Period
| optional
The frequency of the PeriodIndex
. You can think of freq
as the interval size of a time span. By default, the frequency is inferred from data
.
4. year
link | int
or array
or Series
| optional
By default, year=None
.
5. month
link | int
or array
or Series
| optional
By default, month=None
.
6. quarter
| int
or array
or Series
| optional
By default, quarter=None
.
7. day
link | int
or array
or Series
| optional
By default, day=None
.
8. hour
| int
or array
or Series
| optional
By default, hour=None
.
9. minute
| int
or array
or Series
| optional
By default, minute=None
.
10. second
| int
or array
or Series
| optional
By default, second=None
.
11. tz
link | object
| optional
The timezone to use when converting from datetime64
to PeriodIndex
. By default, tz=None
.
Return Value
A PeriodIndex
object.
Examples
Basic usage
To create a PeriodIndex
using a list of date-strings:
index_period = pd.PeriodIndex(["2020-12-25", "2020-12-26"], freq="D")index_period
PeriodIndex(['2020-12-25', '2020-12-26'], dtype='period[D]', freq='D')
Here, the freq="D"
means that the interval size of each period is a day.
We can then use this PeriodIndex
as the index of our DataFrame like so:
A2020-12-25 a2020-12-26 b
Specifying freq
To specify an interval size of the PeriodIndex
, set freq
like so:
index_period = pd.PeriodIndex(["2020-12-25", "2020-12-26"], freq="2D")index_period
PeriodIndex(['2020-12-25', '2020-12-26'], dtype='period[2D]', freq='2D')
Specifying individual time parameters
Instead of passing in data
, you can create a PeriodIndex
using individual time parameters like so:
idx = pd.PeriodIndex(year=[2000, 2002], month=[5,6], day=[10,11], freq="D")idx
PeriodIndex(['2000-05-10', '2002-06-11'], dtype='period[D]', freq='D')
Specifying tz
To make the PeriodIndex timezone-aware:
pd.PeriodIndex(["2020-12-25"], freq="D", tz="Asia/Tokyo")
PeriodIndex(['2020-12-25'], dtype='period[D]', freq='D')