Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
What is PeriodIndex?
A PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time. It's useful for representing time periods with specific frequencies like days, months, or years.
Creating a PeriodIndex
First, import pandas and create a PeriodIndex object with daily frequency ?
import pandas as pd
# Create a PeriodIndex object with daily frequency
periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")
print("PeriodIndex...")
print(periodIndex)
PeriodIndex... PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], dtype='period[D]')
Getting Days from PeriodIndex
Use the .day property to extract the day component from each period ?
import pandas as pd
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 frequency
print("PeriodIndex frequency:")
print(periodIndex.freq)
# Extract day component from each period
print("\nThe day numbers from the PeriodIndex:")
print(periodIndex.day)
PeriodIndex frequency: <Day> The day numbers from the PeriodIndex: Index([25, 30, 20, 15, 12, 18], dtype='int64')
Understanding the Results
The day property returns an Index containing the day component of each period. For example, '2018-07-25' returns 25, '2019-10-30' returns 30, and so on.
Conclusion
Use pd.PeriodIndex() to create time period objects and the .day property to extract day components. This is useful for time-based data analysis and filtering operations.
