pandas - 未来警告:不推荐将 datetime64-dtype 数据传递给 TimedeltaIndex
问题描述
我有一个测量值数据集及其相应的时间戳,格式为 hh:mm:ss,其中 hh 可以> 24 h。
对于机器学习任务,需要对数据进行插值,因为分别有多个具有不同时间戳的测量值。对于重采样和插值,我发现索引的 dtype 应该是日期时间格式。对于进一步的数据处理和机器学习任务,我需要再次使用 timedelta 格式。
这是一些代码:
Res_cont = Res_cont.set_index('t_a') #t_a is the column of the timestamps for the measured variable a from a dataframe
#Then, I need to change datetime-format for resampling and interpolation, otherwise timedate are not like 00:15:00, but like 00:15:16 for example
Res_cont.index = pd.to_datetime(Res_cont.index)
#first, upsample to seconds, then interpolate linearly and downsample to 15min steps, lastly
Res_cont = Res_cont.resample('s').interpolate(method='linear').resample('15T').asfreq().dropna()
Res_cont.index = pd.to_timedelta(Res_cont.index) #Here is, where the error ocurred
不幸的是,我收到以下错误消息:
FutureWarning:不推荐将 datetime64-dtype 数据传递给 TimedeltaIndex,这将在未来版本中引发 TypeError Res_cont = pd.to_timedelta(Res_cont.index)
很明显,我提供的代码的最后一行存在问题。我想知道,如何更改此代码以防止将来版本中出现类型错误。不幸的是,我不知道如何解决它。
也许你能帮忙?
编辑:这里有一些任意样本数据:
t_a = ['00:00:26', '00:16:16', '00:25:31', '00:36:14', '25:45:44']
a = [0, 1.3, 2.4, 3.8, 4.9]
Res_cont = pd.Series(data = a, index = t_a)
解决方案
您可以DatetimeIndex.strftime
用于将输出日期时间转换为HH:MM:SS
格式:
t_a = ['00:00:26', '00:16:16', '00:25:31', '00:36:14', '00:45:44']
a = [0, 1, 2, 3, 4]
Res_cont = pd.DataFrame({'t_a':t_a,'a':a})
print (Res_cont)
t_a a
0 00:00:26 0
1 00:16:16 1
2 00:25:31 2
3 00:36:14 3
4 00:45:44 4
Res_cont = Res_cont.set_index('t_a')
Res_cont.index = pd.to_datetime(Res_cont.index)
Res_cont=Res_cont.resample('s').interpolate(method='linear').resample('15T').asfreq().dropna()
Res_cont.index = pd.to_timedelta(Res_cont.index.strftime('%H:%M:%S'))
print (Res_cont)
a
00:15:00 0.920000
00:30:00 2.418351
00:45:00 3.922807
推荐阅读
- python - 将嵌套列表中的值返回到 PandasDataFrame
- c - 在文件 C 中构造 fscanf
- javascript - 添加两个“document.getElementById”来计算偏移量Top
- tensorflow - keras.layers.TimeDistributed with Huggingface Transformer 给出 NotImplementedError
- wildcard - 我需要将除一个以外的所有文件从一个目录复制到另一个
- openlayers - 通过 OLCesium 启用 Cesium 的 requestRenderMode
- android - android studio中的WebView
- javascript - 数组的值未显示在特定 div 内
- angular - Angular 9 在数组中添加多个对象会覆盖现有数组
- javascript - 这就是范围的全部吗?