Home >Backend Development >Python Tutorial >How to Filter Pandas DataFrames by Date Within the Next Two Months?

How to Filter Pandas DataFrames by Date Within the Next Two Months?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 18:08:02971browse

How to Filter Pandas DataFrames by Date Within the Next Two Months?

Filter Pandas DataFrames on Dates

Problem:

You want to extract rows from a DataFrame that fall within a specific date range, excluding dates outside that range. In this case, you need to keep rows within the next two months.

Solution:

There are several approaches to filtering Pandas DataFrames based on dates:

1. Index-Based Indexing (If 'date' Column is the Index):

  • Use .loc for label-based indexing to select rows within a date range:
df.loc['2023-04-01':'2023-06-01']
  • Use .iloc for positional indexing if 'date' is not the index but is a column:
df.iloc[start_index:end_index]  # Select rows by position

2. Non-Index-Based Indexing (If 'date' Column is Not the Index):

  • Temporarily set 'date' as the index or permanently if it represents time-series data:
df.set_index('date', inplace=True)
  • Use boolean indexing to filter rows:
df[(df['date'] > '2023-04-01') & (df['date'] < '2023-06-01')]

Note:

  • .ix has been deprecated.
  • For additional information and examples, refer to the Pandas documentation: [Indexing](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection)

The above is the detailed content of How to Filter Pandas DataFrames by Date Within the Next Two Months?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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