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
Selected Reading
Python Pandas - Get the day of the week from the PeriodIndex object
To get the day of the week from the PeriodIndex object, use the PeriodIndex.weekday property. This property returns the day of the week as integers, where Monday=0, Tuesday=1, Wednesday=2, Thursday=3, Friday=4, Saturday=5, and Sunday=6.
Creating a PeriodIndex Object
First, let's create a PeriodIndex object with datetime strings and specify the frequency ?
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 the Day of Week
Use the weekday property to extract the day of the week 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")
# Get day of week (Monday=0, Sunday=6)
weekdays = periodIndex.weekday
print("Day of week from PeriodIndex:")
print(weekdays)
# Display with actual day names for clarity
day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print("\nCorresponding day names:")
for i, day_num in enumerate(weekdays):
print(f"{periodIndex[i].strftime('%Y-%m-%d')}: {day_names[day_num]}")
Day of week from PeriodIndex: Index([5, 2, 3, 5], dtype='int64') Corresponding day names: 2021-09-25: Saturday 2019-10-30: Wednesday 2021-07-15: Thursday 2022-06-25: Saturday
Complete Example
Here's a comprehensive example showing PeriodIndex properties including weekday ?
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")
print("PeriodIndex:")
print(periodIndex)
print("\nFrequency object:")
print(periodIndex.freq)
print("\nFrequency as string:")
print(periodIndex.freqstr)
print("\nWeek numbers:")
print(periodIndex.week)
print("\nDay of week (0=Monday, 6=Sunday):")
print(periodIndex.weekday)
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]') Frequency object: <Minute> Frequency as string: T Week numbers: Index([38, 44, 28, 25], dtype='int64') Day of week (0=Monday, 6=Sunday): Index([5, 2, 3, 5], dtype='int64')
Conclusion
The weekday property of PeriodIndex returns integer values representing days of the week, with Monday as 0 and Sunday as 6. This is useful for time-based analysis and filtering operations in pandas.
Advertisements
