python - 从 Pandas Dataframe 的滚动时间窗口中识别重复项

标签 python pandas

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

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/

相关文章:

python - 使用索引不会更改 numpy 元素值

java - 如何从Python程序创建的文件中读取java程序中的RDD

python - 如何使用日期时间索引和列连接多个数据帧?

python - 使用 DatetimeIndex 重新采样 DataFrame 并保留日期范围

python - 使用 Excel Pandas 中的浮点值填充字典时出现问题

python - 仅从 BeautifulSoup 获取数字而不是整个 div

python - 在 TCP/IP python 中添加编码和解码的位置

python - 在Python中运行adb管道命令

python - 如何将时间序列数据分割成3列和3 channel ?

python - 如何在箱形图2上绘制来自不同数据帧的数据 - Python