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 - Extract the frequency object as a string from the DateTimeIndex
To extract the frequency object as a string from the DateTimeIndex, use the DateTimeIndex.freqstr property in Pandas. This property returns the frequency as a string representation, which is useful for displaying or storing the frequency information.
Creating a DateTimeIndex with Frequency
First, let's create a DateTimeIndex with a specific frequency ?
import pandas as pd
# Create DatetimeIndex with period 6 and frequency as D (daily)
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+10:30', '2021-10-21 02:30:50+10:30',
'2021-10-22 02:30:50+10:30', '2021-10-23 02:30:50+10:30',
'2021-10-24 02:30:50+10:30', '2021-10-25 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='D')
Extracting Frequency as String
Now let's extract the frequency information using different properties ?
import pandas as pd
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
# Display frequency object
print("DateTimeIndex frequency object:")
print(datetimeindex.freq)
# Display frequency as string using freqstr
print("\nDateTimeIndex frequency as string:")
print(datetimeindex.freqstr)
DateTimeIndex frequency object: <Day> DateTimeIndex frequency as string: D
Different Frequency Examples
Let's see how freqstr works with different frequency types ?
import pandas as pd
# Weekly frequency
weekly_index = pd.date_range('2021-01-01', periods=4, freq='W')
print("Weekly frequency string:", weekly_index.freqstr)
# Monthly frequency
monthly_index = pd.date_range('2021-01-01', periods=4, freq='M')
print("Monthly frequency string:", monthly_index.freqstr)
# Hourly frequency
hourly_index = pd.date_range('2021-01-01', periods=4, freq='H')
print("Hourly frequency string:", hourly_index.freqstr)
# Business day frequency
business_index = pd.date_range('2021-01-01', periods=4, freq='B')
print("Business day frequency string:", business_index.freqstr)
Weekly frequency string: W-SUN Monthly frequency string: M Hourly frequency string: H Business day frequency string: B
Conclusion
The freqstr property provides a simple way to get the frequency of a DateTimeIndex as a string. This is useful for debugging, logging, or when you need to store frequency information in a readable format.
Advertisements
