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 rule code applied on the given DateOffset object
In Pandas, you can retrieve the rule code applied to a DateOffset object using the rule_code property. This property returns the frequency string used to create the offset.
Syntax
offset.rule_code
Example
Let's create a DateOffset and examine its rule code ?
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 months here using the "M" frequency
offset = to_offset("3M")
# Display the DateOffset
print("\nDateOffset...\n", offset)
# Display the Updated Timestamp
print("\nUpdated Timestamp...\n", timestamp + offset)
# Return the rule code of the frequency applied on the given DateOffset object
print("\nThe rule code of the DateOffset object...\n", offset.rule_code)
The output of the above code is ?
Timestamp... 2021-09-26 03:25:02.000045 DateOffset... <3 * MonthEnds> Updated Timestamp... 2021-11-30 03:25:02.000045 The rule code of the DateOffset object.. M
Different DateOffset Types
Let's explore rule codes for various DateOffset types ?
from pandas.tseries.frequencies import to_offset
# Create different types of DateOffsets
day_offset = to_offset("5D")
week_offset = to_offset("2W")
business_offset = to_offset("3B")
year_offset = to_offset("Y")
# Display their rule codes
print("Day offset rule code:", day_offset.rule_code)
print("Week offset rule code:", week_offset.rule_code)
print("Business day offset rule code:", business_offset.rule_code)
print("Year offset rule code:", year_offset.rule_code)
Day offset rule code: D Week offset rule code: W Business day offset rule code: B Year offset rule code: A
Key Points
- The
rule_codereturns the base frequency string without multipliers - For "3M", the rule code is "M" (not "3M")
- This property is useful for identifying the frequency type of an offset
- Common rule codes include 'D' (day), 'W' (week), 'M' (month), 'A' (year), 'B' (business day)
Conclusion
The rule_code property provides the base frequency identifier for any DateOffset object. It's particularly useful when you need to programmatically determine the frequency type without the multiplier.
Advertisements
