【问题标题】:pandas filter rows from dataframe with consecutive difference < npandas 从具有连续差异的数据帧中过滤行 < n
【发布时间】:2020-04-23 06:05:06
【问题描述】:

我有一个 pandas 这样的数据框:

id         time
1             1
2             3
3             4
4             5
5             8
6             8

我想删除相隔不到 2 秒的行。我首先计算连续行之间的时间差异并将其添加为列:

df['time_since_last_detect'] = df.time.diff().fillna(0)

导致:

id         time       time_since_last_detect
1             1                            0
2             3                            2
3             4                            1
4             5                            1
5             8                            3
6             8                            0

然后使用df[df.time_since_last_detect &gt; 1] 过滤行,结果是:

id         time       time_since_last_detect
2             3                            2
5             8                            3

但是,这样做的问题是,一旦删除了一行,它就不会重新计算与新的前一行的差异。例如,在删除第一行和第三行之后,第二行和第四行之间的差值为 2。但是第四行仍然会被这个过滤器删除,我不希望发生这种情况。解决此问题的最佳方法是什么?这是我想要达到的结果:

id         time       time_since_last_detect
2             3                            2
4             5                            1
5             8                            3

【问题讨论】:

  • 您在这个问题中的第二个数据框与您的第一个不匹配。请参见第一个数据帧中的 id = 1, time= 0 和第二个数据帧中的 time =1。你能澄清一下吗?
  • @ScottBoston 是的,很抱歉造成混乱!我现在修好了

标签: python pandas


【解决方案1】:

不是一个完美的解决方案,但您可以根据自己的情况执行以下操作。需要在下面进行修改以制作通用功能。

import pandas as pd

d = {'id' : [1,2,3,4,5,6], 'time' : [1,3,4,5,8,8]}
df = pd.DataFrame(data =d)

df['time_since_last_detect'] = df.time.diff().fillna(0)
timeperiod = 2

df['time_since_last_sum'] =  df['time_since_last_detect'].rolling(min_periods=1, window=timeperiod).sum().fillna(0) # gets sum of rolling period , in this case 2. One case change as needed

df_final =  df.loc[(df['time_since_last_detect'] >= 2) | (df['time_since_last_sum'] == 2)] # Filter data with 2 OR condition 1. If last_detect>2 or last of 2 rolling period is 2 

输出:

   id  time  time_since_last_detect  time_since_last_sum
   2     3                     2.0                  2.0
   4     5                     1.0                  2.0
   5     8                     3.0                  4.0

【讨论】:

  • 它似乎有效..你能解释一下你的解决方案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
  • 2017-04-29
  • 2019-11-21
  • 2021-12-29
  • 2019-01-06
  • 2016-11-23
相关资源
最近更新 更多