【问题标题】:Detecting missing timestamp检测丢失的时间戳
【发布时间】:2019-04-18 00:30:48
【问题描述】:

我有以下具有时间戳和值的数据框。时间戳增加 5 秒,并注意到 23:02:02 和 23:06:32 之间有缺失记录。

有没有简单的方法来检测时间戳之间是否有缺失记录?

timestamp   value
23:01:27    2915
23:01:32    2916
23:01:37    2919
23:01:42    2924
23:01:47    2926
23:01:52    2928
23:01:57    2933
23:02:02    2937 # <- missing timestamp
23:06:32    3102 # <- between these lines
23:06:37    3109
23:06:42    3114
23:06:47    3122
23:06:52    3126
23:06:57    3129

【问题讨论】:

    标签: python pandas dataframe time-series


    【解决方案1】:

    如果您的目标是指出在哪里您缺少时间戳,您可以转换为日期时间并使用diff 查看行之间的时间差,然后使用&gt;'00:00:05' 查看是否有差距大于 5 秒:

    >>> pd.to_datetime(df['timestamp']).diff() > '00:00:05'
    0     False
    1     False
    2     False
    3     False
    4     False
    5     False
    6     False
    7     False
    8      True
    9     False
    10    False
    11    False
    12    False
    13    False
    Name: timestamp, dtype: bool
    

    这表明您缺少索引8以上的记录

    如果您的目标只是查看是否您缺少时间戳,请使用any

    >>> (pd.to_datetime(df['timestamp']).diff() > '00:00:05').any()
    True
    

    表明您确实在某处缺少时间戳

    [EDIT] 根据@JoranBeasley 的建议,您还可以使用您的时差模式来推断所需的频率:

    d = pd.to_datetime(df['timestamp']).diff()
    
    >>> (d > d.mode()[0])
    0     False
    1     False
    2     False
    3     False
    4     False
    5     False
    6     False
    7     False
    8      True
    9     False
    10    False
    11    False
    12    False
    13    False
    Name: timestamp, dtype: bool
    

    因为d.mode()[0] 将返回观察到的最常见频率:

    >>> d.mode()[0]
    Timedelta('0 days 00:00:05')
    

    【讨论】:

    • 如果 OP 只是想知道数据中是否有 any 缺失记录,他们不能只比较该集合中预期记录的数量吗?帧与实际记录数?即使他们不知道时间范围,我们难道不能利用第一条记录和最后一条记录之间的时间差来查找该信息吗?
    【解决方案2】:

    您可以使用.diff()来计算相邻时间戳之间的差异是否大于某个阈值(例如7秒)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多