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 - Get the week of the period from the PeriodIndex object
To get the week number of the period from a PeriodIndex object, use the PeriodIndex.week property. This property returns the week of the year for each period in the index.
What is PeriodIndex?
A PeriodIndex is an immutable array holding ordinal values that represent regular periods in time. It's useful for time-based indexing and analysis in pandas.
Creating a PeriodIndex Object
First, let's create a PeriodIndex object with datetime strings ?
import pandas as pd
# Create a PeriodIndex object with minute frequency
periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'], freq="T")
print("PeriodIndex...")
print(periodIndex)
PeriodIndex... PeriodIndex(['2021-09-25 07:30', '2019-10-30 04:15', '2021-07-15 02:55', '2022-06-25 09:40'], dtype='period[T]')
Getting Week Numbers
Use the .week property to extract the week number from each period ?
import pandas as pd
periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'], freq="T")
# Display week numbers from the PeriodIndex object
week_numbers = periodIndex.week
print("Week numbers from the PeriodIndex object:")
print(week_numbers)
Week numbers from the PeriodIndex object: Index([38, 44, 28, 25], dtype='int64')
Complete Example
Here's a comprehensive example showing PeriodIndex creation and week extraction ?
import pandas as pd
# Create a PeriodIndex object
periodIndex = pd.PeriodIndex(['2021-09-25 07:30:35', '2019-10-30 04:15:45',
'2021-07-15 02:55:15', '2022-06-25 09:40:55'], freq="T")
# Display PeriodIndex object
print("PeriodIndex...")
print(periodIndex)
# Display PeriodIndex frequency
print("\nPeriodIndex frequency object...")
print(periodIndex.freq)
# Display PeriodIndex frequency as string
print("\nPeriodIndex frequency object as a string...")
print(periodIndex.freqstr)
# Display week from the PeriodIndex object
print("\nThe week from the PeriodIndex object...")
print(periodIndex.week)
PeriodIndex... PeriodIndex(['2021-09-25 07:30', '2019-10-30 04:15', '2021-07-15 02:55', '2022-06-25 09:40'], dtype='period[T]') PeriodIndex frequency object... <Minute> PeriodIndex frequency object as a string... T The week from the PeriodIndex object... Index([38, 44, 28, 25], dtype='int64')
Understanding the Results
The week numbers represent the ISO week number within the year:
- Week 38: September 25, 2021
- Week 44: October 30, 2019
- Week 28: July 15, 2021
- Week 25: June 25, 2022
Conclusion
The PeriodIndex.week property provides an easy way to extract week numbers from period data. This is particularly useful for time series analysis and grouping operations based on weeks.
