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 - Return the frequency object as a string from the PeriodIndex object
To return the frequency object as a string from the PeriodIndex object, use the PeriodIndex.freqstr property. This property provides a string representation of the frequency, which is useful for display and debugging purposes.
Creating a PeriodIndex Object
First, let's create a PeriodIndex object with datetime values and a specific frequency ?
import pandas as pd
# Create a PeriodIndex object with minute frequency
periodIndex = pd.PeriodIndex(['2021-09-25 07:50:35', '2019-10-30 04:35:45',
'2021-07-15 02:25:15', '2022-06-25 07:20:55'], freq="T")
print("PeriodIndex object:")
print(periodIndex)
PeriodIndex object: PeriodIndex(['2021-09-25 07:50', '2019-10-30 04:35', '2021-07-15 02:25', '2022-06-25 07:20'], dtype='period[T]')
Using freqstr Property
The freqstr property returns the frequency as a string representation ?
import pandas as pd
periodIndex = pd.PeriodIndex(['2021-09-25 07:50:35', '2019-10-30 04:35:45',
'2021-07-15 02:25:15', '2022-06-25 07:20:55'], freq="T")
# Compare frequency object vs frequency string
print("Frequency object:")
print(periodIndex.freq)
print("\nFrequency as string:")
print(periodIndex.freqstr)
print(f"\nType of freqstr: {type(periodIndex.freqstr)}")
Frequency object: <Minute> Frequency as string: T Type of freqstr: <class 'str'>
Different Frequency Examples
Here are examples with different frequency types ?
import pandas as pd
# Daily frequency
daily_idx = pd.PeriodIndex(['2021-01-01', '2021-01-02', '2021-01-03'], freq='D')
print(f"Daily frequency string: {daily_idx.freqstr}")
# Monthly frequency
monthly_idx = pd.PeriodIndex(['2021-01', '2021-02', '2021-03'], freq='M')
print(f"Monthly frequency string: {monthly_idx.freqstr}")
# Hourly frequency
hourly_idx = pd.PeriodIndex(['2021-01-01 10:00', '2021-01-01 11:00'], freq='H')
print(f"Hourly frequency string: {hourly_idx.freqstr}")
Daily frequency string: D Monthly frequency string: M Hourly frequency string: H
Conclusion
The freqstr property provides a convenient way to get the string representation of a PeriodIndex frequency. This is particularly useful when you need to display or store frequency information in a human-readable format.
Advertisements
