如何解决numpy.linalg.lstsq报UFuncTypeError类型转换错误?
解决numpy.linalg.lstsq的UFuncTypeError类型转换问题
问题场景
我是Python初学者,将numpy导入为py,使用py.linalg.lstsq做线性OLS回归预测RIC次日值时,触发错误:UFuncTypeError: Cannot cast ufunc 'lstsq_n' input 0 from dtype('O') to dtype('float64') with casting rule 'same_kind',目标是实现Eikon Python API教程13分46秒处的结果。
相关代码
# 用滞后数据列构成的矩阵,通过线性OLS回归预测RIC次日值 regs = {} for ric in rics: df = dfs[ric] # 获取当前RIC的数据 reg = py.linalg.lstsq(df[cols], df[ric], rcond=-1)[0] regs[ric] = reg # 存储回归结果
报错堆栈
--------------------------------------------------------------------------- UFuncTypeError Traceback (most recent call last) Cell In [214], line 6 4 for ric in rics: 5 df = dfs[ric] # 获取当前RIC的数据 ----> 6 reg = py.linalg.lstsq(df[cols], df[ric], rcond=-1)[0] File <__array_function__ internals>:180, in lstsq(*args, **kwargs) File ~\miniconda3\lib\site-packages\numpy\linalg\linalg.py:2300, in lstsq(a, b, rcond) 2297 if n_rhs == 0: 2298 # lapack无法处理n_rhs=0,所以在该轴上分配更大的数组 2299 b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype) -> 2300 x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj) 2301 if m == 0: 2302 x[...] = 0 UFuncTypeError: Cannot cast ufunc 'lstsq_n' input 0 from dtype('O') to dtype('float64') with casting rule 'same_kind'
数据样例
df[cols](特征矩阵)
lag_1 lag_2 lag_3 lag_4 lag_5 Date 2022-01-24 2.967 2.989 2.997 2.929 2.919 2022-01-25 2.982 2.967 2.989 2.997 2.929 2022-01-26 2.984 2.982 2.967 2.989 2.997 2022-01-27 2.975 2.984 2.982 2.967 2.989 2022-01-28 3.011 2.975 2.984 2.982 2.967 ... ... ... ... ... ... 2022-11-22 3.891 3.842 3.83 3.843 3.868 2022-11-23 3.921 3.891 3.842 3.83 3.843 2022-11-25 3.909 3.921 3.891 3.842 3.83 2022-11-29 3.833 3.909 3.921 3.891 3.842 2022-11-30 3.829 3.833 3.909 3.921 3.891 195 rows × 5 columns
df[ric](目标变量)
Date 2022-01-24 2.982 2022-01-25 2.984 2022-01-26 2.975 2022-01-27 3.011 2022-01-28 3.018 ... 2022-11-22 3.921 2022-11-23 3.909 2022-11-25 3.833 2022-11-29 3.829 2022-11-30 3.821 Name: MYMK180001=, Length: 195, dtype: Float64
解决方法
报错核心原因是df[cols]的数据类型为object(即dtype('O')),而numpy的lstsq要求输入数值型数组(如float64),按以下步骤修复:
强制转换数据类型
在传入lstsq前,将特征矩阵和目标变量统一转为float64类型,修改代码如下:regs = {} for ric in rics: df = dfs[ric] # 转换特征矩阵和目标变量为float64 X = df[cols].astype('float64') y = df[ric].astype('float64') reg = py.linalg.lstsq(X, y, rcond=-1)[0] regs[ric] = reg清理非数值数据
如果转换时报错,说明数据中存在字符串、空值等非数值元素,先执行数据清洗:# 将非数值转为NaN,再删除含NaN的行 df[cols] = df[cols].apply(pd.to_numeric, errors='coerce') df = df.dropna(subset=cols + [ric])处理缺失值
若不想删除缺失行,可填充默认值(如均值):df[cols] = df[cols].fillna(df[cols].mean())
内容的提问来源于stack exchange,提问作者han api
相关产品推荐
相关产品推荐

