Home > Article > Backend Development > How to Filter Pandas DataFrames by Date Range for the Next Two Months?
When dealing with time-series data in Pandas, it's often necessary to filter rows based on specific date ranges. This article addresses how to efficiently filter a Pandas DataFrame to retain only rows within the next two months.
If the 'date' column is set as the index of the DataFrame, you can use label-based indexing or positional indexing to extract the desired rows. For instance, to select rows with dates within the next two months:
df.loc['2023-03-01':'2023-04-30'] # Label-based indexing df.iloc[pd.date_range('2023-03-01', '2023-04-30', freq='D').index] # Positional indexing
If the 'date' column is not the index, you have two options:
df[(df['date'] >= '2023-03-01') & (df['date'] <= '2023-04-30')]
Note that the .ix accessor is deprecated, and it's recommended to use .loc or .iloc instead.
The above is the detailed content of How to Filter Pandas DataFrames by Date Range for the Next Two Months?. For more information, please follow other related articles on the PHP Chinese website!