按日期过滤 Pandas DataFrames [英] Filtering Pandas DataFrames on dates
问题描述
我有一个带有日期"列的 Pandas DataFrame.现在我需要过滤掉 DataFrame 中日期在接下来两个月之外的所有行.本质上,我只需要保留接下来两个月内的行.
实现这一目标的最佳方法是什么?
如果日期列是索引,则使用 .loc 进行基于标签的索引或使用 .iloc 进行位置索引.
例如:
df.loc['2014-01-01':'2014-02-01']
在此处查看详细信息http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection
如果该列不是索引,您有两个选择:
- 将其设为索引(临时或永久,如果是时间序列数据)
df[(df['date'] > '2013-01-01') &(df['date'] <'2013-02-01')]
请参阅此处了解一般说明>
注意:.ix 已弃用.
I have a Pandas DataFrame with a 'date' column. Now I need to filter out all rows in the DataFrame that have dates outside of the next two months. Essentially, I only need to retain the rows that are within the next two months.
What is the best way to achieve this?
If date column is the index, then use .loc for label based indexing or .iloc for positional indexing.
For example:
df.loc['2014-01-01':'2014-02-01']
See details here http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection
If the column is not the index you have two choices:
- Make it the index (either temporarily or permanently if it's time-series data)
df[(df['date'] > '2013-01-01') & (df['date'] < '2013-02-01')]
See here for the general explanation
Note: .ix is deprecated.
这篇关于按日期过滤 Pandas DataFrames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!