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 - Display the quarter of the date from the PeriodIndex object
To display the quarter of the date from the PeriodIndex object, use the PeriodIndex.quarter property. A quarter represents a three-month period in a year: Q1 (Jan-Mar), Q2 (Apr-Jun), Q3 (Jul-Sep), and Q4 (Oct-Dec).
What is PeriodIndex?
PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time. It's useful for time series data analysis with fixed frequencies.
Creating a PeriodIndex Object
First, import pandas and create a PeriodIndex 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]')
Displaying Quarter Information
Use the quarter property to extract quarter values from the PeriodIndex ?
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 the quarter of each date
print("Quarter of each date:")
print(periodIndex.quarter)
# Display frequency information
print("\nFrequency object:", periodIndex.freq)
print("Frequency as string:", periodIndex.freqstr)
Quarter of each date: Index([3, 4, 3, 2], dtype='int64') Frequency object: <Minute> Frequency as string: T
Understanding the Results
The quarter property returns an Index with integer values representing quarters ?
| Date | Month | Quarter |
|---|---|---|
| 2021-09-25 | September | 3 (Q3: Jul-Sep) |
| 2019-10-30 | October | 4 (Q4: Oct-Dec) |
| 2021-07-15 | July | 3 (Q3: Jul-Sep) |
| 2022-06-25 | June | 2 (Q2: Apr-Jun) |
Conclusion
The PeriodIndex.quarter property efficiently extracts quarter information from datetime periods. This is useful for quarterly financial analysis and seasonal data grouping in pandas time series operations.
