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 applied on the given DateOffset object
To return the frequency applied on the given DateOffset object, use the offset.freqstr property in Pandas. The freqstr attribute returns the string representation of the frequency used to create the DateOffset.
Creating a DateOffset
First, let's create a DateOffset object using to_offset() function ?
from pandas.tseries.frequencies import to_offset
import pandas as pd
# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')
# Display the Timestamp
print("Timestamp...\n", timestamp)
# Create the DateOffset
# We are incrementing the days here using the "D" frequency
offset = to_offset("5D")
# Display the DateOffset
print("\nDateOffset...\n", offset)
Timestamp... 2021-09-26 03:25:02.000045 DateOffset... <5 * Days>
Using freqstr Property
The freqstr property returns the frequency string that was used to create the DateOffset ?
from pandas.tseries.frequencies import to_offset
import pandas as pd
# Set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-09-26 03:25:02.000045')
# Create the DateOffset with 5 days frequency
offset = to_offset("5D")
# Display the Updated Timestamp
print("Updated Timestamp...\n", timestamp + offset)
# Return the frequency applied on the given DateOffset object
print("\nThe frequency on the DateOffset object...\n", offset.freqstr)
Updated Timestamp... 2021-10-01 03:25:02.000045 The frequency on the DateOffset object... 5D
Different Frequency Examples
Here are examples with different frequency strings ?
from pandas.tseries.frequencies import to_offset
# Different frequency examples
frequencies = ["3H", "2W", "1M", "6MS"]
for freq in frequencies:
offset = to_offset(freq)
print(f"Frequency: {freq} ? freqstr: {offset.freqstr}")
Frequency: 3H ? freqstr: 3H Frequency: 2W ? freqstr: 2W Frequency: 1M ? freqstr: M Frequency: 6MS ? freqstr: 6MS
Conclusion
The freqstr property is useful for retrieving the frequency string from a DateOffset object. This helps in understanding what frequency was applied and can be used for validation or debugging purposes.
Advertisements
