Python Pandas PeriodIndex - Convert the PeriodArray to the specified frequency


To convert the PeriodArray to the specified frequency, use the periodIndex.asfreq() method.

At first, import the required libraries −

import pandas as pd

Create a PeriodIndex object −

periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2020-07-15 02:55:15', '2022-06-25 09:40:55'], freq="Y")

Display PeriodIndex object −

print("PeriodIndex...\n", periodIndex)

Convert to the specified frequency. We have set the frequency as the parameter of the asfreq() −

print("\nConvert..\n", periodIndex.asfreq('M'))

Example

Following is the code −

import pandas as pd

# Create a PeriodIndex object
# PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time
# We have set the frequency using the "freq" parameter
periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2020-07-15 02:55:15', '2022-06-25 09:40:55'], freq="Y")

# Display PeriodIndex object
print("PeriodIndex...\n", periodIndex)

# Display PeriodIndex frequency
print("\nPeriodIndex frequency object...\n", periodIndex.freq)

# Display PeriodIndex frequency as string
print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr)

# Convert to the specified frequency
# We have set the frequency as the parameter of the asfreq()
print("\nConvert..\n", periodIndex.asfreq('M'))

Output

This will produce the following code −

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

PeriodIndex frequency object...
<YearEnd: month=12>

PeriodIndex frequency object as a string...
A-DEC

Convert..
PeriodIndex(['2021-12', '2019-12', '2020-12', '2022-12'], dtype='period[M]')

Updated on: 21-Oct-2021

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements