How to filter a Pandas DataFrame for specific dates
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
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
Related Articles
Continue your learning journey with these related topics
Filtering
5 min readHow to create a subset of a DataFrame in Pandas
Create a subset of a Pandas DataFrame by using indexing operator [] and providing desired columns or a condition based on values of one or more columns, e.g. df[['col1', 'col2']] or df[df['col3'] > 0.5].
3/20/2023Read More
Getting Started
1 min readHow to slice a Pandas DataFrame
Learn various ways to slice a Pandas DataFrame, including using the .loc[], .iloc[], and [] accessors, boolean indexing and chaining multiple conditions to select specific rows and columns.
2/16/2023Read More
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