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 set frequency
To create a PeriodIndex, use the pandas.PeriodIndex() method. To set the frequency, use the freq parameter for representing regular periods in time.
What is PeriodIndex?
A PeriodIndex is an immutable ndarray that holds ordinal values indicating regular periods in time. It's useful for time series data where you want to represent periods rather than timestamps.
Creating a Basic PeriodIndex
Here's how to create a PeriodIndex with daily frequency ?
import pandas as pd
# Create a PeriodIndex with daily frequency
period_index = pd.PeriodIndex(['2021-09-25', '2020-10-30', '2020-11-20'], freq="D")
print("PeriodIndex...")
print(period_index)
PeriodIndex... PeriodIndex(['2021-09-25', '2020-10-30', '2020-11-20'], dtype='period[D]')
Different Frequency Options
You can use various frequency parameters to create different period types ?
import pandas as pd
# Monthly frequency
monthly = pd.PeriodIndex(['2021-09', '2021-10', '2021-11'], freq="M")
print("Monthly PeriodIndex:")
print(monthly)
# Yearly frequency
yearly = pd.PeriodIndex(['2021', '2022', '2023'], freq="Y")
print("\nYearly PeriodIndex:")
print(yearly)
Monthly PeriodIndex: PeriodIndex(['2021-09', '2021-10', '2021-11'], dtype='period[M]') Yearly PeriodIndex: PeriodIndex(['2021', '2022', '2023'], dtype='period[Y-DEC]')
Accessing Period Properties
You can extract specific components from the PeriodIndex ?
import pandas as pd
period_index = pd.PeriodIndex(['2021-09-25', '2020-10-30', '2020-11-20'], freq="D")
print("Original PeriodIndex:")
print(period_index)
print("\nDay component:")
print(period_index.day)
print("\nMonth component:")
print(period_index.month)
print("\nYear component:")
print(period_index.year)
Original PeriodIndex: PeriodIndex(['2021-09-25', '2020-10-30', '2020-11-20'], dtype='period[D]') Day component: Index([25, 30, 20], dtype='int64') Month component: Index([9, 10, 11], dtype='int64') Year component: Index([2021, 2020, 2020], dtype='int64')
Common Frequency Codes
| Code | Description | Example |
|---|---|---|
| D | Daily | 2021-09-25 |
| M | Monthly | 2021-09 |
| Y | Yearly | 2021 |
| Q | Quarterly | 2021Q3 |
Conclusion
Use pd.PeriodIndex() with the freq parameter to create period-based time indices. PeriodIndex is ideal for representing regular time periods in data analysis and time series operations.
