Sling Academy
Home/Pandas/Pandas BusinessDay.is_on_offset() method (5 examples)

Pandas BusinessDay.is_on_offset() method (5 examples)

Last updated: February 21, 2024

Introduction

Pandas, a powerful Python data analysis toolkit, has made dealing with date and time data much easier and more efficient. One of its lesser-known, yet incredibly powerful features is the BusinessDay.is_on_offset() method. This method is part of Pandas’ offsets module, which is designed to make working with business days straightforward. In this tutorial, we’ll explore the BusinessDay.is_on_offset() method with 5 practical examples. Whether you’re a beginner or an experienced Pandian, understanding how to leverage this method can streamline your time series data manipulation tasks significantly.

What does BusinessDay.is_on_offset() do?

Before diving into examples, let’s cover some basics. The BusinessDay.is_on_offset() method checks if a given date is a valid business day or not. A business day typically refers to any day when normal business operations are conducted, which usually excludes weekends and public holidays. However, the exact definition of a business day can vary based on locale and specific business rules.

Example 1: Basic Usage

from pandas.tseries.offsets import BusinessDay

# Create a BusinessDay object
bday = BusinessDay()

# Check if a specific date is a business day
print(bday.is_on_offset('2023-04-05'))  # Assuming this is a Wednesday with no public holiday

# Output: True

This basic example showcases the direct use of the is_on_offset() method to check if a typical Wednesday (with no public holiday) is considered a business day.

Example 2: Dealing with Holidays

from pandas.tseries.offsets import BusinessDay, CustomBusinessDay
from pandas.tseries.holiday import USFederalHolidayCalendar

# Create a CustomBusinessDay object with US Federal holidays
us_bd = CustomBusinessDay(calendar=USFederalHolidayCalendar())

# Check if the 4th of July is a business day
print(us_bd.is_on_offset('2023-07-04'))  # 4th of July is a US Federal Holiday

# Output: False

This example uses a CustomBusinessDay object with the US Federal Holiday Calendar to determine if Independence Day, a federal holiday, is considered a business day.

Example 3: Custom Business Rules

from pandas.tseries.offsets import CustomBusinessDay

# Define a custom weekend to include Fridays
week_custom = CustomBusinessDay(weekmask='Mon Tue Wed Thu')

# Check if a Friday falls under the custom business day definition
print(week_custom.is_on_offset('2023-04-07'))  # A typical Friday

# Output: False

In this more advanced scenario, we alter the default definition of a business week to exclude Fridays, demonstrating the flexibility of CustomBusinessDay.

Example 4: International Business Days

from pandas.tseries.offsets import CustomBusinessDay
from pandas.tseries.holiday import AbstractHolidayCalendar, EasterMonday, GoodFriday

class UKHolidayCalendar(AbstractHolidayCalendar):
    rules = [
        GoodFriday(),
        EasterMonday()
    ]

uk_bd = CustomBusinessDay(calendar=UKHolidayCalendar())

# Check if Good Friday is a business day in the UK
print(uk_bd.is_on_offset('2023-04-07'))  # Good Friday

# Output: False

Here, we create a CustomBusinessDay object for the UK that accounts for Good Friday and Easter Monday holidays, essential for global businesses or data analysts dealing with international data.

Example 5: Adjusting Dates Within DataFrames

import pandas as pd
from pandas.tseries.offsets import BusinessDay

df = pd.DataFrame({
    'date': ['2023-04-07', '2023-04-10', '2023-04-11'],
    'value': [10, 20, 30]
})

df['date'] = pd.to_datetime(df['date'])

# Adjust dates to the nearest business day
df['adjusted_date'] = df['date'].apply(lambda x: x if BusinessDay().is_on_offset(x) else x + BusinessDay())

print(df)

# Example output might look like this:
#          date  value adjusted_date
# 0 2023-04-07     10    2023-04-10
# 1 2023-04-10     20    2023-04-10
# 2 2023-04-11     30    2023-04-11

This final example illustrates how to use BusinessDay.is_on_offset() within a Pandas DataFrame to adjust dates so they fall on business days. This is particularly useful for financial and time series analysis, where aligning dates to business days can be critical.

Conclusion

In conclusion, the BusinessDay.is_on_offset() method is a versatile tool in the Pandas library that enables precise control over Working Days computation. By using a combination of this method with custom configurations and different calendars, one can accurately model business day logic specific to any requirement. This flexibility facilitates more accurate and meaningful data analysis across various contexts.

Next Article: Understanding CustomBusinessDay in Pandas (5 examples)

Previous Article: Understanding PeriodIndex in Pandas (6 examples)

Series: DateFrames in Pandas

Pandas

You May Also Like

  • How to Use Pandas Profiling for Data Analysis (4 examples)
  • How to Handle Large Datasets with Pandas and Dask (4 examples)
  • Pandas – Using DataFrame.pivot() method (3 examples)
  • Pandas: How to ‘FULL JOIN’ 2 DataFrames (3 examples)
  • Pandas: Select columns whose names start/end with a specific string (4 examples)
  • 3 ways to turn off future warnings in Pandas
  • How to Integrate Pandas with Apache Spark
  • How to Use Pandas for Web Scraping and Saving Data (2 examples)
  • How to Clean and Preprocess Text Data with Pandas (3 examples)
  • Pandas – Using Series.replace() method (3 examples)
  • Pandas json_normalize() function: Explained with examples
  • Pandas: Reading CSV and Excel files from AWS S3 (4 examples)
  • Using pandas.Series.rank() method (4 examples)
  • Pandas: Dropping columns whose names contain a specific string (4 examples)
  • Pandas: How to print a DataFrame without index (3 ways)
  • Fixing Pandas NameError: name ‘df’ is not defined
  • Pandas – Using DataFrame idxmax() and idxmin() methods (4 examples)
  • Pandas FutureWarning: ‘M’ is deprecated and will be removed in a future version, please use ‘ME’ instead
  • Pandas: Checking equality of 2 DataFrames (element-wise)