首页 文章

在日期过滤Pandas DataFrames

提问于
浏览
60

我有一个带有“日期”列的Pandas DataFrame . 现在我需要过滤掉DataFrame中具有接下来两个月之外的日期的所有行 . 基本上,我只需要保留未来两个月内的行 .

实现这一目标的最佳方法是什么?

5 回答

  • 5

    如果 date column is the index ,则使用.loc进行基于标签的索引,或使用.iloc进行位置索引 .

    例如:

    df.loc['2014-01-01':'2014-02-01']
    

    在这里查看详细信息http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection

    如果列是 not the index ,您有两个选择:

    • 将其设为索引(如果是时间序列数据,则为临时或永久)

    • df[(df['date'] > '2013-01-01') & (df['date'] < '2013-02-01')]

    有关一般说明,请参阅here

    注意:.ix已弃用 .

  • 107

    以前的答案在我的经验中是不正确的,你不能传递一个简单的字符串,需要是一个datetime对象 . 所以:

    import datetime 
    df.loc[datetime.date(year=2014,month=1,day=1):datetime.date(year=2014,month=2,day=1)]
    
  • 9

    如果您的日期通过导入日期时间包标准化,您可以简单地使用:

    df[(df['date']>datetime.date(2016,1,1)) & (df['date']<datetime.date(2016,3,1))]
    

    要使用datetime包标记日期字符串,可以使用此功能:

    import datetime
    datetime.datetime.strptime
    
  • 27

    如果日期在索引中,则只需:

    df['20160101':'20160301']
    
  • 18

    如果您的datetime列具有Pandas日期时间类型(例如 datetime64[ns] ),为了正确过滤,您需要pd.Timestamp object,例如:

    from datetime import date
    
    import pandas as pd
    
    value_to_check = pd.Timestamp(date.today().year, 1, 1)
    filter_mask = df['date_column'] < value_to_check
    filtered_df = df[filter_mask]
    

相关问题