【问题标题】:How to slice a Pandas Time Series using a logical expression involving dates如何使用涉及日期的逻辑表达式对 Pandas 时间序列进行切片
【发布时间】:2018-11-19 07:21:28
【问题描述】:

我想了解 Pandas 中的时间序列切片,我正在研究在涉及日期的逻辑语句中组合(组合和,或,非操作数)条件的可能性。

所以这是一个可重现的例子:

HAO_10
Date         Price
2018-01-02  30.240000
2018-01-03  30.629999
2018-01-04  30.860001
2018-01-05  31.010000
2018-01-08  31.389999
2018-01-09  31.309999
2018-01-10  31.400000
2018-01-11  31.580000
2018-01-12  31.680000
2018-01-16  31.200001

HAO_10.iloc[((HAO_10.index < datetime.strptime('2018-01-04', '%Y-%m-%d')) | 

             ((HAO_10.index > datetime.strptime('2018-01-08', '%Y-%m-%d')) & 
        (HAO_10.index  != datetime.strptime('2018-01-12', '%Y-%m-%d')))), ]

这是尝试剔除与 2018-01-04 之前和 2018-01-08 之后的日期相对应的值,而不是与日期 2018-01-12 相对应的值。

有效。

有没有更优雅的方法来完成同样的事情?

【问题讨论】:

    标签: python pandas time-series slice logical-operators


    【解决方案1】:

    首先使用pd.to_datetime 转换为日期时间。然后,您可以在 loc 语句中使用日期字符串:

    df['Date'] = pd.to_datetime(df['Date'])
    
    # This says: find where date is not between your range and not equal to 01-12
    df.loc[(~df['Date'].between('2018-01-04','2018-01-08')) & (df['Date'] != '2018-01-12')]
    
            Date      Price
    0 2018-01-02  30.240000
    1 2018-01-03  30.629999
    5 2018-01-09  31.309999
    6 2018-01-10  31.400000
    7 2018-01-11  31.580000
    9 2018-01-16  31.200001
    

    【讨论】:

      【解决方案2】:

      首先使用date_rangeunion 创建已删除值的DatetimeIndex,然后仅选择带有原始索引的difference

      idx = pd.date_range('2018-01-04','2018-01-08').union(['2018-01-12'])
      df = HAO_10.loc[HAO_10.index.difference(idx)]
      #another similar solutions
      #df = HAO_10.drop(idx, errors='ignore')
      #df = HAO_10[~HAO_10.index.isin(idx)]
      

      如果只想使用dates 并且index 还包含times floor 是你的朋友:

      df = HAO_10.loc[HAO_10.index.floor('d').difference(idx)]
      #another similar solutions
      #df = HAO_10[~HAO_10.index.floor('d').isin(idx)]
      
      print (df)
                      Price
      2018-01-02  30.240000
      2018-01-03  30.629999
      2018-01-09  31.309999
      2018-01-10  31.400000
      2018-01-11  31.580000
      2018-01-16  31.200001
      

      您的解决方案应该是简化:

      df = HAO_10[((HAO_10.index < '2018-01-04') | ((HAO_10.index > '2018-01-08') & 
                        (HAO_10.index  != '2018-01-12')))]
      

      【讨论】:

      • 这很聪明!我喜欢那个解决方案
      猜你喜欢
      • 2018-12-11
      • 2012-12-15
      • 2016-01-18
      • 2020-04-09
      • 2014-06-27
      • 2020-12-10
      • 2018-09-26
      • 2021-06-04
      相关资源
      最近更新 更多