【问题标题】:Drop Duolicates in a Panda DataFrame for timestampe in a certain threshold在特定阈值的时间戳中删除 Panda DataFrame 中的重复项
【发布时间】:2023-01-05 23:16:11
【问题描述】:

我有一个 Dataframe 如下,并且想删除关于三列的重复项:userurltimestamp(仅当它小于或等于最后一次出现的 <= 10 sec 时)。在这里,我用 # 评论详细说明行:

    timestamp                   user    url
0   2018-02-07 00:00:00+02:00   ip0     google.com # first occurrence
1   2018-02-07 00:00:02+02:00   ip1     xe.com # first occurrence
2   2018-02-07 00:00:10+02:00   ip7     facebook.com
3   2018-02-07 00:00:11+02:00   ip1     xe.com # duplicate: ( <= 10 sec ) : drop
4   2018-02-07 00:00:15+02:00   ip2     example.com
5   2018-02-07 00:00:20+02:00   ip3     ebay.com
6   2018-02-07 00:00:55+02:00   ip1     xe.com # not a duplicate : leave it
7   2018-02-07 00:00:59+02:00   ip5     amazon.com
8   2018-02-07 00:01:02+02:00   ip1     xe.com # duplicate: ( <= 10 sec ) : drop
9   2018-02-07 00:01:28+02:00   ip0     google.com # not a duplicate : leave it

我尝试了df = df.drop_duplicates(subset=['user', 'url'], keep='first'),它删除了所有可能的重复项,而不管timestamp

我的预期结果应该是这个样子:

    timestamp                   user    url
0   2018-02-07 00:00:00+02:00   ip0     google.com
1   2018-02-07 00:00:02+02:00   ip1     xe.com
2   2018-02-07 00:00:10+02:00   ip7     facebook.com
4   2018-02-07 00:00:15+02:00   ip2     example.com
5   2018-02-07 00:00:20+02:00   ip3     ebay.com
6   2018-02-07 00:00:55+02:00   ip1     xe.com
7   2018-02-07 00:00:59+02:00   ip5     amazon.com
9   2018-02-07 00:01:28+02:00   ip0     google.com

在我的示例中,创建某种掩码以排除属于特定阈值(例如 10 秒)的行的最简单方法是什么?

干杯,

【问题讨论】:

  • 如果您有一行在 10 秒内是重复的行,并且该行已经是您要删除的重复行,您也会删除它吗?就像你的数据一样,如果你有这个额外的行2018-02-07 00:00:13+02:00 ip1 xe.com,它在 10 秒内与你的行号 3 重复,但是因为你将删除行索引 3,那么它就足够了你的行号 1?
  • 这实际上是一个很好的观察结果,谢谢,我会用您提出的行更新我的问题!但是为了回答你的问题,我会说我的主要意图是第一个被识别的事件,然后在timestamp中寻找可能的重复项!因此,我将检查您建议的行,其中仍然是第一次出现 2018-02-07 00:00:02+02:00 ip1 xe.com # first occurrence

标签: python pandas dataframe duplicates mask


【解决方案1】:

我将从时间戳列中创建一个附加列 - 秒,然后执行如下操作:

df = pd.concat([df[df['seconds']<=10].drop_duplicates(subset=['timestamp', 'user', 'url'], keep='first'), df[df['seconds']>10]])

不过我觉得还有一种更简洁方便的方式。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 2018-03-22
    • 2021-12-15
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2013-08-22
    • 2015-07-26
    相关资源
    最近更新 更多