How to filter a Pandas DataFrame for specific dates

1 min readFilteringPandasDataFrameDates
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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')]
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.