在数据帧中找到最近的日期时间位置,从中减去500毫秒,并将其存储在新的数据帧中

2024-04-29 12:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

失败时间戳:

ts_failure = datetime.datetime(2019, 5, 15, 19, 48, 2, 495)

与数据帧中的失败时间戳最接近的时间戳是(2019, 5, 15, 19, 48, 2, 479)

数据帧:

Timestamp  
2019-05-15 19:48:02.477  
2019-05-15 19:48:02.478  
2019-05-15 19:48:02.479  

我想在故障时间戳附近找到最近的时间戳,并使用时间增量减去500毫秒,然后打印出新的数据帧,该数据帧的时间戳从(t-500)ms到故障时间的最近时间。你知道吗

我试图用iloc找到最近的索引,但是收到一个明显的错误,说我不能比较timestamp和int。 df.index.get_loc(ts_failure, method='nearest')

TypeError: '<' not supported between instances of 'Timestamp' and 'int'

无法获取abs差异,因为我需要毫秒范围内最接近的时间戳。你知道吗

df.iloc[(df['Timestamp']-ts_failure).abs().argsort()[:]]

感谢您的帮助:)


Tags: 数据dfdatetimefailure错误时间abs增量
2条回答

试试这个:

ts_failure = datetime.datetime(2019, 5, 15, 19, 48, 2, 495)
nearest_idx = np.searchsorted(df['Timestamp'], ts_failure) - 1
nearest_time = df.iloc[nearest_idx]['Timestamp']
t_500ms = nearest_time - pd.Timedelta(milliseconds = 500)
df.index = df['Timestamp']
df2 = df.loc[t_500ms: nearest_time]

您应该更改ts_failure的表示形式:

ts_failure = pd.to_datetime(pd.Timestamp(2019, 5, 15, 19, 48, 2, 495000)) 
df.iloc[df.set_index('Timestamp').index.get_loc(ts_failure, method='nearest')]

Timestamp   2019-05-15 19:48:02.479
Name: 2, dtype: datetime64[ns]

请注意,时间戳总是以纳秒为单位。所以把时间戳的最后一个值乘以1000。你知道吗

相关问题 更多 >