Pandas DataFrame to_period() method with examples

Spread the love

The to_period() method in pandas Convert DataFrame from DatetimeIndex to PeriodIndex with desired frequency (inferred from index if not passed).

Syntax –

DataFrame.to_period(freq=None, axis=0, copy=True)

freq – Frequency of the PeriodIndex.

axis – {0 or ‘index’, 1 or ‘columns’}, default 0. The axis to convert (the index by default).

copy – If False then underlying input data is not copied.

Examples –

Let’s create a Datetime index.

import pandas as pd

idx = pd.to_datetime(
    ["2020-03-31 00:00:00",
     "2021-05-31 00:00:00",
     "2022-08-31 00:00:00",]
DatetimeIndex(['2020-03-31', '2021-05-31', '2022-08-31'], dtype='datetime64[ns]', freq=None)

Let’s convert to Monthly frequency

PeriodIndex(['2020-03', '2021-05', '2022-08'], dtype='period[M]')

For yearly frequency we can write

PeriodIndex(['2020', '2021', '2022'], dtype='period[A-DEC]')

Rating: 1 out of 5.

Leave a Reply