Python Pandas - Create a PeriodIndex and get the days of the period



To create a PeriodIndex, use the pandas.PeriodIndex() method. Get the days of the period using the PeriodIndex.day property.

At first, import the required libraries −

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(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

Display PeriodIndex object −

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

Display day from the PeriodIndex object −

print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

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(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], freq="D") # Display PeriodIndex object print("PeriodIndex...\n", periodIndex) # Display PeriodIndex frequency print("\nPeriodIndex frequency...\n", periodIndex.freq) # Display day from the PeriodIndex object print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

Output

This will produce the following code −

PeriodIndex... PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], dtype='period[D]') PeriodIndex frequency... <Day> The number of days from the PeriodIndex... Int64Index([25, 30, 20, 15, 12, 18], dtype='int64')
Updated on: 2021-10-20T11:31:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements