错误:numpy.core._exceptions.UFuncTypeError: ufunc ‘true_divide’ cannot use operands with types dtype(‘float64’) and dtype(‘<m8[ns]’)
报错源代码:
使用日期作为x轴,float作为y轴传入interp1d()
报错原因是,如果用两个日期相减(上图x_hi-x_lo)会得到一个 Timedelta类型或者说是numpy的<m8[ns]类型,这是带单位的,不能跟作为除数。
解决的方法是将日期转换为float类型。
几种时间类型:
_newX = np.array(["2017-11-24 17:30:00"])
print(_newX.dtype,type(_newX[0]))
_newX = pd.to_datetime(_newX,format = '%Y-%m-%d %H:%M:%S')
print(_newX.dtype,type(_newX[0]))
<U19 <class ‘numpy.str_’>
datetime64[ns] <class ‘pandas._libs.tslibs.timestamps.Timestamp’>
_newX = np.datetime64('2019-01-01')
print(_newX.dtype,type(_newX))
datetime64[D] <class ‘numpy.datetime64’>
转换:
X_0=pd.read_excel(excelFilePath)["日期"].values
print(X_0,X_0.dtype,type(X_0[1]))
X_0 = X_0.astype(numpy.int64)
print(X_0,X_0.dtype,type(X_0[1]))
注意使用的是numpy.int64而不是numpy.int32或者int
[‘2010-08-24T00:00:00.000000000’ ‘2010-08-25T00:00:00.000000000’
‘2010-08-26T00:00:00.000000000’ … ‘2022-04-06T00:00:00.000000000’
‘2022-04-07T00:00:00.000000000’ ‘2022-04-08T00:00:00.000000000’] datetime64[ns] <class ‘numpy.datetime64’>
[1282608000000000000 1282694400000000000 1282780800000000000 …
1649203200000000000 1649289600000000000 1649376000000000000] int64 <class ‘numpy.int64’>
_newX = np.datetime64('2019-01-01')
print(_newX,_newX.dtype,type(_newX))
_newX = _newX.astype(numpy.int64)
print(_newX,_newX.dtype,type(_newX))
2019-01-01 datetime64[D] <class ‘numpy.datetime64’>
17897 int64 <class ‘numpy.int64’>
这里转换是不对应的,需要先把日期转换成上面原始数据的单位(datetime64[ns])再转换成int64,否则会报错“ValueError: A value in x_new is below the interpolation range.”
可以直接指定单位:_newX = np.datetime64('2019-01-01T00:00:00','ns')
或者批量转换:_newX = _newX.astype("datetime64[ns]")
上面的数据放到插值函数就能算出某个日期对应的值了
IRFunction = interp1d(X_0, Y_0, kind = 'linear')
Fill_Y = IRFunction(_newX)