【问题标题】:Drop Duplicates in a DataFrame where a column are identical and have near timestamps在 DataFrame 中删除重复项,其中列相同且时间戳接近
【发布时间】:2021-02-10 17:08:51
【问题描述】:

目前我有以下数据框:

    index         timestamp      | id_a | id_b | id_pair
   --------------------------------------------------------
     0       2020-01-01 00:00:00 | 1    | A    |   1A
     1       2020-01-01 00:01:30 | 1    | A    |   1A
     2       2020-01-01 00:02:30 | 1    | A    |   1A
     3       2020-01-01 00:07:30 | 1    | A    |   1A
     4       2020-01-01 00:00:00 | 2    | B    |   2B
     5       2000-01-01 00:00:00 | 3    | C    |   3C
     6       2000-01-01 00:00:00 | 4    | D    |   4D

对于数据框,我想删除具有相同 id_pair 和时间戳的行,范围为 X 分钟,比如说 5 分钟。因此预期的结果是这样的:

    index         timestamp      | id_a | id_b | id_pair
   --------------------------------------------------------
     0       2020-01-01 00:00:00 | 1    | A    |   1A
     3       2020-01-01 00:07:30 | 1    | A    |   1A
     4       2020-01-01 00:00:00 | 2    | B    |   2B
     5       2000-01-01 00:00:00 | 3    | C    |   3C
     6       2000-01-01 00:00:00 | 4    | D    |   4D

在搜索 stackoverflow 问题后,我偶然发现了这个与我的问题类似的问题
Drop Duplicates in a DataFrame if Timestamps are Close, but not Identical



我重新创建了代码,使其符合我的需求(几乎相同),代码如下所示

mask1 = df.groupby('id_pair').timestamp.apply(lambda x: x.diff().dt.seconds < 300)
mask2 = df.unique_contact.duplicated(keep=False) & (mask1 | mask1.shift(-1))
df[~mask2]

但是当我运行代码时,我遇到了这个错误:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

任何帮助或建议将不胜感激
在此先感谢



Python 版本:3.6.12
熊猫版本:0.25.3

【问题讨论】:

  • @Gouri 抱歉,我已经更新了问题,以便为您提供更多背景信息。

标签: python python-3.x pandas dataframe timestamp


【解决方案1】:

首先将列转换为datetimes,然后为预期的输出删除| mask1.shift(-1)

df['timestamp'] = pd.to_datetime(df['timestamp'])
mask1 = df.groupby('id_pair').timestamp.apply(lambda x: x.diff().dt.seconds < 300)
mask2 = df.id_pair.duplicated(keep=False) & mask1
df = df[~mask2]
print (df)
   index  timestamp  id_a id_b id_pair
0      0 2020-01-01     1    A      1A
2      2 2020-01-01     2    B      2B
3      3 2000-01-01     3    C      3C
4      4 2000-01-01     4    D      4D

【讨论】:

  • 那么是不是只使用&amp; mask1 而不是| mask1.shift(-1) 我可以保留时间戳在5分钟范围内的重复项?
  • @AnindhitoIrmandharu - 我用新的样本数据对其进行了测试并且运行良好,我更改了删除 | mask1.shift(-1) 的解决方案以获得您的预期输出。
  • 是的,以前它也已经工作了,我只是对思考过程感到好奇。感谢您的帮助,非常感谢。
猜你喜欢
  • 2018-03-22
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 2013-08-22
  • 2018-08-23
相关资源
最近更新 更多