【问题标题】:How to correctly modify timestamps on streaming data to create unique indexes如何正确修改流数据的时间戳以创建唯一索引
【发布时间】:2018-05-26 22:09:39
【问题描述】:

我们正在流式传输的数据类型取自以不规则方式输出数据的 PI System。这在时间序列数据中并不少见,因此我尝试为每个时间戳添加 1 秒左右以确保索引是唯一的。但是,这并没有像我希望的那样起作用,因为我一直收到类型错误。

我已尝试实施 (Modifying timestamps in pandas to make index unique) 中突出显示的解决方案,但没有任何成功。

我得到的错误信息是:

TypeError: ufunc add cannot use operands with types dtype('O') and dtype('<m8')

代码实现如下:

values = Slugging_Sep.index.duplicated(keep=False).astype(float)
values[values==0] = np.NaN

missings = np.isnan(values)
cumsum = np.cumsum(~missings)
diff = np.diff(np.concatenate(([0.], cumsum[missings])))
values[missings] = -diff

# print result
result = Slugging_Sep.index + np.cumsum(values).astype(np.timedelta64)
print(result)

我的尝试

  • 类型转换 - 我认为计算是由于两个 不同的类型被添加在一起,但这还没有解决 问题。
  • 在 Pandas 中使用时间增量 - 这会产生相同的类型错误。

    pd.to_timedelta(Slugging_Sep.groupby('Time').cumcount(), unit='ms'))
    Slugging_Sep['Time'] = (str(Slugging_Sep['Time'] + 
    pd.to_timedelta(Slugging_Sep.groupby('Time').cumcount(), unit='ms')))
    

所以我有两个问题:

  1. 谁能给我一些关于如何解决这个问题的建议 未来的时间序列问题?
  2. 实际上是什么dtype ('&lt;m8')

谢谢。

【问题讨论】:

  • 您能否提供一些测试用例的示例输入和预期输出?此外,请避免发布数据的屏幕截图 - 只需在线发布实际数据即可。以这种方式提供帮助要容易得多。
  • 我最好的猜测是 Slugging_Sep.index 不是正确的日期时间。您是否尝试在添加 timedelta 之前使用 pd.to_datetime() 对其进行转换?

标签: python pandas numpy time-series


【解决方案1】:

根据 Alex Zisman 的建议,我通过以下行重新转换了 Slugging_Sep.index:

pd.to_datetime(Slugging_Sep['Time'])
Slugging_Sep.set_index('Time', inplace=True)

然后我实现了从我提到的上述 SO 链接中获取的以下代码:

#values = Slugging_Sep.index.duplicated(keep=False).astype(float)
#values[values==0] = np.NaN

#missings = np.isnan(values)
#cumsum = np.cumsum(~missings)
#diff = np.diff(np.concatenate(([0.], cumsum[missings])))
#values[missings] = -diff

# print result
#result = Slugging_Sep.index + np.cumsum(values).astype(np.timedelta64())
#Slugging_Sep.index = result
#print(Slugging_Sep.index)

这解决了这个问题,并为每个重复的时间戳添加了纳秒,因此它成为一个唯一的索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    相关资源
    最近更新 更多