Python interp1d()插值错误 ‘<m8[ns]‘

错误: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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nickdlk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值