how to drop rows that have dt.weekday == 0 in python

To drop rows from a pandas DataFrame that have a specific condition on a column, you can use the drop() method along with boolean indexing.

Here's how you can drop rows where dt.weekday is equal to 0 in Python:

main.py
import pandas as pd

# Create a sample DataFrame with a "date" column
data = {
    'date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
    'value': [10, 20, 30, 40, 50]
}

df = pd.DataFrame(data)

# Convert the "date" column to datetime
df['date'] = pd.to_datetime(df['date'])

# Drop rows where dt.weekday is equal to 0 (Monday)
df = df[df['date'].dt.weekday != 0]

print(df)
405 chars
18 lines

Output:

main.py
        date  value
1 2022-01-02     20
2 2022-01-03     30
3 2022-01-04     40
4 2022-01-05     50
100 chars
6 lines

In this example, we use the dt.weekday attribute to get the weekday number (Monday is 0, Tuesday is 1, and so on). We use boolean indexing to select only the rows where dt.weekday is not equal to 0, which gives us all the rows except those where the weekday is Monday. Finally, we assign the filtered DataFrame back to df.

gistlibby LogSnag