我有一个数据框,我想在其中识别(并最终删除)滑动时间窗口内的重复行。
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
提前致谢。
最佳答案
我正在创建一个临时列 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
关于python - 从 Pandas Dataframe 的滚动时间窗口中识别重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66847995/