为什么从列表创建 float32 数组会引发值错误?

Why creating a float32 array from a list raises value error?

我正在尝试创建一个 float32 数组,如下所示,

np.float32([kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist])

但是,我收到以下错误,

ValueError: setting an array element with a sequence.

我尝试按如下方式将其显式转换为 numpy 数组并重试,但我仍然遇到相同的错误

np.array([kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist]).astype(float)

我错过了什么?

使用 dtype 参数指定数据类型 np.array()

np.array([kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist], dtype=float)

这是一个产生错误的例子:

In [910]: np.array([1,[1,2,3],4])                                                              
Out[910]: array([1, list([1, 2, 3]), 4], dtype=object)

没有 float 转换很好 - 但随后出现错误:

In [911]: np.array([1,[1,2,3],4]).astype(float)                                                
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: float() argument must be a string or a number, not 'list'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-911-9c007059d6ad> in <module>
----> 1 np.array([1,[1,2,3],4]).astype(float)

ValueError: setting an array element with a sequence.

我怀疑 [kp2, kp2+dir_v*dist, kp2 + dir_v_r*dist] 包含数字、数组、列表的混合,生成对象 dtype 数组。

如果列表确实包含数字和数字列表(或数组)的混合,hstack 可能就是您想要的:

In [922]: np.hstack([1,[1,2,3],4])                                                             
Out[922]: array([1, 1, 2, 3, 4])