我有一个(这里非常简单) Pandas 数据框,看起来像这样:
df
datetime user type msg
0 2012-11-11 15:41:08 u1 txt hello world
1 2012-11-11 15:41:11 u2 txt hello world
2 2012-11-21 17:00:08 u3 txt hello world
3 2012-11-22 18:08:35 u4 txt hello you
4 2012-11-22 18:08:37 u5 txt hello you
我现在想做的是获取所有时间戳在 3 秒内的重复消息。所需的输出将是:
datetime user type msg
0 2012-11-11 15:41:08 u1 txt hello world
1 2012-11-11 15:41:11 u2 txt hello world
3 2012-11-22 18:08:35 u4 txt hello you
4 2012-11-22 18:08:37 u5 txt hello you
没有第三行,因为它的文本与第一行和第二行相同,但它的时间戳不同 3秒以内。
我试图将列 datetime 和 msg 定义为 duplicate()
方法的参数,但它返回一个空数据帧,因为时间戳不相同:
mask = df.duplicated(subset=['datetime', 'msg'], keep=False)
print(df[mask])
Empty DataFrame
Columns: [datetime, user, type, msg, MD5]
Index: []
有没有一种方法可以为我的“日期时间”参数定义一个范围?为了说明,某事 喜欢:
mask = df.duplicated(subset=['datetime_between_3_seconds', 'msg'], keep=False)
如有任何帮助,我们将一如既往地非常感激。
最佳答案
这段代码给出了预期的输出
df[(df.groupby(["msg"], as_index=False)["datetime"].diff().fillna(0).dt.seconds <= 3).reset_index(drop=True)]
我对数据框的“msg”列进行了分组,然后选择了该数据框的“datetime”列并使用了内置函数 diff . Diff 函数查找该列的值之间的差异。用零填充 NaT 值并仅选择那些值小于 3 秒的索引。
在使用上面的代码之前,请确保您的数据框按日期时间按升序排序。
关于python - Pandas 数据框 : duplicates based on column and time range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44777114/