如何对日期时间和浮点数进行插值

1 投票
2 回答
7538 浏览
提问于 2025-04-18 15:21

我正在使用 scipy 进行一维插值,处理时间序列数据。我的x轴数据是日期时间格式,而y轴数据是浮点数,像这样:

3/15/2012 16:00:00  32.94
3/16/2012 16:00:00  32.95
3/19/2012 16:00:00  32.61

现在在计算斜率的时候,使用的公式是 slope = (y_hi-y_lo) / (x_hi-x_lo),但我遇到了一个错误 TypeError: unsupported operand type(s) for /: 'float' and 'datetime.timedelta',这显然是个错误。有没有人能给我一些建议,怎么解决这个问题呢?

2 个回答

3

如果你在处理时间序列数据,Pandas这个工具非常不错。下面是一个例子,演示如何通过插值把每天的数据提升到每小时的数据:

import numpy as np
from pandas import *
rng = date_range('1/1/2011', periods=12, freq='D')
ts = Series(np.arange(len(rng)), index=rng)
resampled = ts.resample('H')
interp = resampled.interpolate()
In [5]: ts
Out[5]:
2011-01-01     0
2011-01-02     1
2011-01-03     2
2011-01-04     3
2011-01-05     4
2011-01-06     5
2011-01-07     6
2011-01-08     7
2011-01-09     8
2011-01-10     9
2011-01-11    10
2011-01-12    11

In [12]: interp.head()
Out[12]:
2011-01-01 00:00:00    0.000000
2011-01-01 01:00:00    0.041667
2011-01-01 02:00:00    0.083333
2011-01-01 03:00:00    0.125000
2011-01-01 04:00:00    0.166667
Freq: H, dtype: float64

In [13]: interp.tail()
Out[13]:
2011-01-11 20:00:00    10.833333
2011-01-11 21:00:00    10.875000
2011-01-11 22:00:00    10.916667
2011-01-11 23:00:00    10.958333
2011-01-12 00:00:00    11.000000
Freq: H, dtype: float64
6

你的问题是你试图把一个浮点数(小数)除以一个 datetime.timedelta 对象,这样做会导致类型错误(TypeError),这点你已经说得很清楚了。

你可以使用 datetime.timedelta.total_seconds() 这个方法,把 datetime.timedelta 对象转换成一个浮点数,表示这个时间段内的总秒数。

这样的话,你可以把你的代码改成类似下面的样子:

slope_numerator = y_hi - y_lo
slope_denominator = (x_hi - x_lo).total_seconds()
slope = slope_numerator / slope_denominator

需要注意的是,这样计算出来的结果是以秒为单位的斜率。如果你想要以小时、天等其他单位来表示,可以调整分母来满足你的需求。

撰写回答