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 - Return the frequency object from the PeriodIndex object
The PeriodIndex.freq property in Pandas returns the frequency object associated with a PeriodIndex. This property is useful for understanding the time interval pattern of your period data.
What is PeriodIndex?
A PeriodIndex is an immutable array that holds ordinal values representing regular periods in time. Each period represents a span of time (like a day, month, or year) rather than a specific timestamp.
Creating a PeriodIndex with Frequency
When creating a PeriodIndex, you specify the frequency using the freq parameter ?
import pandas as pd
# Create a PeriodIndex with daily frequency
periodIndex = pd.PeriodIndex(['2021-09-25', '2019-10-30', '2020-11-20',
'2021-07-15', '2022-06-12', '2023-07-10'], freq="D")
print("PeriodIndex:")
print(periodIndex)
PeriodIndex: PeriodIndex(['2021-09-25', '2019-10-30', '2020-11-20', '2021-07-15', '2022-06-12', '2023-07-10'], dtype='period[D]')
Accessing the Frequency Object
Use the freq property to retrieve the frequency object ?
import pandas as pd
periodIndex = pd.PeriodIndex(['2021-09-25', '2019-10-30', '2020-11-20',
'2021-07-15', '2022-06-12', '2023-07-10'], freq="D")
# Get the frequency object
frequency = periodIndex.freq
print("Frequency object:", frequency)
print("Frequency type:", type(frequency))
Frequency object: <Day> Frequency type: <class 'pandas._libs.tslibs.offsets.Day'>
Different Frequency Examples
Here are examples with different frequency settings ?
import pandas as pd
# Monthly frequency
monthly_periods = pd.PeriodIndex(['2021-01', '2021-02', '2021-03'], freq="M")
print("Monthly frequency:", monthly_periods.freq)
# Quarterly frequency
quarterly_periods = pd.PeriodIndex(['2021Q1', '2021Q2', '2021Q3'], freq="Q")
print("Quarterly frequency:", quarterly_periods.freq)
# Yearly frequency
yearly_periods = pd.PeriodIndex(['2021', '2022', '2023'], freq="Y")
print("Yearly frequency:", yearly_periods.freq)
Monthly frequency: <MonthEnd> Quarterly frequency: <QuarterEnd: startingMonth=12> Yearly frequency: <YearEnd: month=12>
Common Frequency Codes
| Frequency Code | Description | Example |
|---|---|---|
| D | Daily | 2021-01-01 |
| M | Monthly | 2021-01 |
| Q | Quarterly | 2021Q1 |
| Y | Yearly | 2021 |
| H | Hourly | 2021-01-01 10:00 |
Conclusion
The freq property provides access to the frequency object of a PeriodIndex, helping you understand the time interval pattern. This is essential for time series analysis and period-based operations in Pandas.
