【问题标题】:Future Warning: Passing datetime64-dtype data to TimedeltaIndex is deprecated未来警告:不推荐将 datetime64-dtype 数据传递给 TimedeltaIndex
【发布时间】:2019-12-16 01:46:49
【问题描述】:

我有一个测量值数据集及其对应的时间戳,格式为 hh:mm:ss,其中 hh 可以大于 24 小时。

对于机器学习任务,需要对数据进行插值,因为有多个测量值分别具有不同的时间戳。 对于重采样和插值,我发现索引的 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)

【问题讨论】:

    标签: pandas typeerror deprecated datetime64


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 很遗憾,这是不可能的。正如我在请求中所写,在我的情况下,重采样和插值必须使用 datetime-index。我试图在我的代码的 cmets 中指定这一点:> 然后,我需要更改日期时间格式以进行重采样和插值,> 否则时间日期不像 00:15:00,而是像 00:15:16 例如跨度>
    • @MaxK。 - 你能创建一些示例数据吗?
    • 我在原始帖子的“编辑”下添加了一些示例数据
    • @MaxK。 - 谢谢,已更改解决方案。
    • @MaxK。 - 你的熊猫版本是什么?
    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2019-03-17
    • 2020-01-31
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多