How to filter a Pandas DataFrame for specific dates

1 min

To filter a Pandas DataFrame for specific dates, use the df.loc[] accessor and provide a boolean condition based on the values of the date column. For example:

# we import the library
import pandas as pd

# Create a sample DataFrame
dates = pd.date_range(start="2021-01-01", end="2022-01-02", freq="D")

# we create the sample dataframe with dates
df = pd.DataFrame({"date": dates,
                   "col1":range(len(dates))})

# We filter for rows that starts on the 2021-06-01 and ends on the 2021-07-01
filtered_df = df[(df["date"] >= "2021-06-01") & (df["date"] <= "2021-07-01")]

# Filter for dates in 2021
filtered_df = df.loc[df['date'].dt.year == 2021]

You can also filter for specific date ranges using the .between() method. For example:

# Filter for dates between 2021-06-01 and 2021-07-01
filtered_df = df.loc[df['date'].between('2021-06-01', '2021-07-01')]