【问题标题】:Identify duplicates from a rolling time window in Pandas Dataframe从 Pandas Dataframe 中的滚动时间窗口中识别重复项
【发布时间】:2021-06-25 02:46:22
【问题描述】:

我有一个数据框,我想在其中识别(并最终删除)滑动时间窗口内的重复行。

dict={
    'type': ['apple','apple','apple','berry','grape','apple'],
    'attr': ['red','green','red','blue','green','red'],
    'timestamp': [ '2021-03-01 12:00:00',
                  '2021-03-01 12:00:30',
                  '2021-03-01 12:01:13',
                  '2021-03-01 12:01:30',
                  '2021-03-01 12:10:00',
                  '2021-03-01 12:11:00',
                 ]
}
df = pd.DataFrame(dict)
df['is_dup'] = False
print(df)
    type   attr            timestamp  is_dup
0  apple    red  2021-03-01 12:00:00   False
1  apple  green  2021-03-01 12:00:30   False
2  apple    red  2021-03-01 12:01:13   False
3  berry   blue  2021-03-01 12:01:30   False
4  grape  green  2021-03-01 12:10:00   False
5  apple    red  2021-03-01 12:11:00   False

在示例中,我的目标是在 'type' 和 'attr' 等于 2 分钟内发生的另一行时将一行标记为重复。所以我想标记索引 2 is_dup=True 因为它匹配索引 0 并且在 2 分钟的时间范围内,但不是第 5 行,因为它的时间戳不在窗口内。

所以生成的数据框看起来像:

    type   attr            timestamp  is_dup
0  apple    red  2021-03-01 12:00:00   False
1  apple  green  2021-03-01 12:00:30   False
2  apple    red  2021-03-01 12:01:13   True
3  berry   blue  2021-03-01 12:01:30   False
4  grape  green  2021-03-01 12:10:00   False
5  apple    red  2021-03-01 12:11:00   False

提前致谢。

【问题讨论】:

标签: python pandas


【解决方案1】:

我正在创建一个临时列diff,它对时差进行分组和存储。然后我单独检查时差是否小于2分钟,然后将is_dup修改为True

df['diff'] = df.groupby(['type', 'attr'])['timestamp'].diff().fillna(pd.Timedelta(seconds=0))
df.loc[(df['diff']>pd.Timedelta(0,'m')) & (df['diff']<=pd.Timedelta(2,'m')), 'is_dup'] = True
df=df.drop(['diff'], axis=1)
print(df)

结果输出是

    type   attr           timestamp  is_dup
0  apple    red 2021-03-01 12:00:00   False
1  apple  green 2021-03-01 12:00:30   False
2  apple    red 2021-03-01 12:01:13    True
3  berry   blue 2021-03-01 12:01:30   False
4  grape  green 2021-03-01 12:10:00   False
5  apple    red 2021-03-01 12:11:00   False

【讨论】:

  • 哇,非常感谢!!
  • df['diff']&gt;pd.Timedelta(0,'m')) 的目的是什么? diff 不是总是积极的吗?
  • @tdy 多行的差异值为零,df['diff']&lt;=pd.Timedelta(2,'m') 将包括它们。我想排除这些零值。
  • 有没有办法将原始行也包含在内? @SKPS
猜你喜欢
  • 2020-07-13
  • 2020-08-14
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 2018-01-28
相关资源
最近更新 更多