【问题标题】:Applying start and endtime as filters to dataframe将开始和结束时间作为过滤器应用于数据框
【发布时间】:2020-11-25 09:03:38
【问题描述】:

我正在研究一个看起来像这样的时间序列数据框,其中包含从 2020 年 1 月到 2020 年 8 月的数据。

    Timestamp            Value
    2020-01-01 00:00:00 -68.95370
    2020-01-01 00:05:00 -67.90175
    2020-01-01 00:10:00 -67.45966
    2020-01-01 00:15:00 -67.07624
    2020-01-01 00:20:00 -67.30549
    .....
    2020-07-01 00:00:00 -65.34212

我正在尝试使用下面数据帧中的 start_time 和 end_time 列对前一个数据帧应用过滤器:

  start_time            end_time
 2020-01-12 16:15:00 2020-01-13 16:00:00
 2020-01-26 16:00:00 2020-01-26 16:10:00
 2020-04-12 16:00:00 2020-04-13 16:00:00
 2020-04-20 16:00:00 2020-04-21 16:00:00
 2020-05-02 16:00:00 2020-05-03 16:00:00

输出应将不在开始和结束时间范围内的所有值分配为零,并保留过滤器中指定的开始和结束时间的值。我尝试对开始时间和结束时间同时应用两个过滤器,但没有奏效。

任何帮助将不胜感激。

【问题讨论】:

  • 你试过pandas的合并功能吗?你能分享你自己的代码吗?

标签: python pandas dataframe


【解决方案1】:

使用merge方法和query外连接的解决方案:

print(df1)
            timestamp     Value <- changed Timestamp to timestamp to avoid name conflict in query
0 2020-01-13 00:00:00 -68.95370 <- also changed data for match
1 2020-01-01 00:05:00 -67.90175
2 2020-01-01 00:10:00 -67.45966
3 2020-01-01 00:15:00 -67.07624
4 2020-01-01 00:20:00 -67.30549
5 2020-07-01 00:00:00 -65.34212

df1.loc[df1.index.difference(df1.assign(key=0).merge(df2.assign(key=0), how = 'outer')\
           .query("timestamp >= start_time and timestamp < end_time").index),"Value"] = 0

结果:

            timestamp    Value
0 2020-01-13 00:00:00 -68.9537
1 2020-01-01 00:05:00   0.0000
2 2020-01-01 00:10:00   0.0000
3 2020-01-01 00:15:00   0.0000
4 2020-01-01 00:20:00   0.0000
5 2020-07-01 00:00:00   0.0000

assign(key=0) 被添加到两个数据框以生成笛卡尔积。

【讨论】:

    【解决方案2】:

    想法是通过Series.between 在列表理解中创建所有掩码,然后通过np.logical_or.reduce 加入logical_or,最后传递给Series.where

    print (df1)
                Timestamp     Value
    0 2020-01-13 00:00:00 -68.95370 <- changed data for match
    1 2020-01-01 00:05:00 -67.90175
    2 2020-01-01 00:10:00 -67.45966
    3 2020-01-01 00:15:00 -67.07624
    4 2020-01-01 00:20:00 -67.30549
    5 2020-07-01 00:00:00 -65.34212
    
    L = [df1['Timestamp'].between(s, e) for s, e in df2[['start_time','end_time']].values]
    m = np.logical_or.reduce(L)
    
    df1['Value'] = df1['Value'].where(m, 0)
    print (df1)
                Timestamp    Value
    0 2020-01-13 00:00:00 -68.9537
    1 2020-01-01 00:05:00   0.0000
    2 2020-01-01 00:10:00   0.0000
    3 2020-01-01 00:15:00   0.0000
    4 2020-01-01 00:20:00   0.0000
    5 2020-07-01 00:00:00   0.0000
    

    【讨论】:

      猜你喜欢
      • 2014-06-27
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多