subset pandas dataframe based on if the day is saturday or sudnay in python

To subset a pandas DataFrame based on if the day is Saturday or Sunday in Python, you can use the dt accessor in combination with the dayofweek property.

Here's an example:

main.py
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'date': pd.date_range(start='1/1/2022', periods=7)})

# Subset the DataFrame based on if the day is Saturday or Sunday
df_subset = df[df['date'].dt.dayofweek.isin([5, 6])]

print(df_subset)
258 chars
10 lines

The output will be a DataFrame that only contains rows where the date is either Saturday or Sunday. The dt.dayofweek property returns the day of the week as an integer, where Monday is 0 and Sunday is 6. Using the isin function, we can check if the day of the week is either 5 (Saturday) or 6 (Sunday) and subset the DataFrame accordingly.

Note that you might need to install pandas if you haven't already by running pip install pandas.

Hope this helps!

related categories

gistlibby LogSnag