Home > Backend Development > Python Tutorial > How to Filter Pandas DataFrame Rows by Date Range?

How to Filter Pandas DataFrame Rows by Date Range?

Susan Sarandon
Release: 2024-12-29 10:03:09
Original
353 people have browsed it

How to Filter Pandas DataFrame Rows by Date Range?

Retrieving DataFrame Rows Within Specified Date Ranges

Problem:

A Pandas DataFrame is created from a CSV file containing a date column. The task is to extract only the rows whose date values fall within a specified date range or between two specified dates.

Solution:

There are two approaches to achieve this:

Option 1: Boolean Masking

  1. Ensure the date column is in datetime64[ns] format.
  2. Create a boolean mask using date range conditions.
  3. Select the desired rows using df.loc[mask].

Example:

import pandas as pd

df = pd.read_csv('data.csv', parse_dates=['date'])

start_date = '2022-01-01'
end_date = '2022-02-28'

mask = (df['date'] >= start_date) & (df['date'] <= end_date)
df_filtered = df.loc[mask]
Copy after login

Option 2: DatetimeIndex

  1. Set the date column as the index of the DataFrame.
  2. Use df.loc[start_date : end_date] to retrieve the desired rows.

Example:

df = pd.read_csv('data.csv', parse_dates=['date'])
df = df.set_index(['date'])

df_filtered = df.loc[start_date : end_date]
Copy after login

Note: If parse_dates was used while reading the CSV, converting the date column to datetime64 is not necessary.

The above is the detailed content of How to Filter Pandas DataFrame Rows by Date Range?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template