To drop rows from a DataFrame in Python using pandas library based on a specific condition, such as excluding rows with dt.weekday 0, 5, or 6, you can use the following code:
main.py346 chars10 lines
In the above code, we first import the pandas library and assume you have a DataFrame named 'df' with a column named 'date' containing date values. We convert the 'date' column to datetime using pd.to_datetime
, if it is not already in datetime format.
Then, we use the .dt.weekday
method to get the weekday for each date value in the 'date' column. We use the .isin([0, 5, 6])
to check if the weekday value is 0, 5, or 6, which correspond to Monday, Saturday, and Sunday respectively. By negating this condition with == False
, we retain only the rows where dt.weekday is not 0, 5, or 6.
Finally, we assign the filtered DataFrame back to 'df' to update it. Now, 'df' will only contain rows where the weekday is not 0, 5, or 6.
Note: Make sure to modify 'df' and 'date' according to your specific DataFrame and column names.
gistlibby LogSnag