How to check whether the day is a weekday or not using Pandas in Python?

How to check whether the day is a weekday or not using Pandas in Python?

In Pandas, you can check if a date is a weekday or a weekend by using the dayofweek attribute of a Timestamp object or DatetimeIndex. The dayofweek attribute returns an integer corresponding to the day of the week, with Monday=0 and Sunday=6.

Here's a simple function that checks if a date is a weekday (Monday through Friday):

import pandas as pd def is_weekday(date): # Convert the date to a pandas Timestamp date = pd.to_datetime(date) # Check if the day of the week is less than 5 (Monday=0, Sunday=6) return date.dayofweek < 5 # Example usage: date_string = "2023-11-06" # For example, November 6, 2023 if is_weekday(date_string): print(f"{date_string} is a weekday.") else: print(f"{date_string} is a weekend.") 

When you run the above code with the date "2023-11-06", it will tell you whether that date is a weekday or not.

Remember, when using pd.to_datetime, you can pass in a string, a Python datetime object, or a numpy datetime64 object, and it will return a Pandas Timestamp. Pandas is quite flexible and can parse many different date formats.

If you have a series of dates and you want to check each one, you can apply this logic to the entire series. Here's an example of how to do that:

# Create a series of dates dates = pd.Series(pd.date_range('2023-11-06', periods=7, freq='D')) # Use the .dt accessor to get the dayofweek and check if it's less than 5 weekdays = dates.dt.dayofweek < 5 # Now weekdays is a boolean series where True indicates a weekday and False indicates a weekend print(weekdays) 

This will give you a series of boolean values corresponding to whether each date is a weekday or not.


More Tags

angular-google-maps var pubmed pagerslidingtabstrip printf qfiledialog jq vtl quicksort kibana

More Programming Guides

Other Guides

More Programming Examples