【问题标题】:Remove all rows between two timestamps from pandas dataframe从熊猫数据框中删除两个时间戳之间的所有行
【发布时间】:2017-06-01 19:27:23
【问题描述】:

如何从两个时间戳包含之间的数据框中删除所有行?

我的数据框看起来像:

                   b      a      
0 2016-12-02 22:00:00  19.218519 
1 2016-12-02 23:00:00  19.171197  
2 2016-12-03 00:00:00  19.257836  
3 2016-12-03 01:00:00  19.195610  
4 2016-12-03 02:00:00  19.176413 

例如:我想从上面的数据帧中删除时间戳介于“2016-12-02 22:00:00”到“2016-12-03 00:00:00”之间的所有行。 因此,结果将仅包含第 3 行和第 4 行。

b列的类型是datetime64,a的类型是float。

请提出建议。

【问题讨论】:

  • 我收到错误:ValueError: labels ['b' ,'a'] not contain in axis

标签: python python-3.x pandas dataframe datetime64


【解决方案1】:

你可以过滤掉那些:

from_ts = '2016-12-02 22:00:00'
to_ts = '2016-12-03 00:00:00'
df = df[(df['b'] < from_ts) | (df['b'] > to_ts)]

【讨论】:

    【解决方案2】:

    将 b 列转换为日期时间,然后应用掩码

    df.b = pd.to_datetime(df.b, format = '%Y-%m-%d %H:%M:%S')
    df[(df.b < '2016-12-02 22:00:00') | (df.b > '2016-12-03 00:00:00')]
    
        b                   a
    3   2016-12-03 01:00:00 19.195610
    4   2016-12-03 02:00:00 19.176413
    

    【讨论】:

      【解决方案3】:
      index_list= df.b[(df.b >= "2016-12-02 22:00:00") & (df.b <= "2016-12-03 00:00:00")].index.tolist()
      df.drop(df.index[index_list] , inplace = True)
      

      【讨论】:

      • 这成功了!没有标签不包含在轴中的错误。此外,它还会从数据框中永久删除这些行。
      猜你喜欢
      • 2018-02-02
      • 1970-01-01
      • 2018-08-18
      相关资源
      最近更新 更多