【发布时间】:2016-05-27 09:18:25
【问题描述】:
最近,我遇到了np.array(list) 转换的问题。假设我们有一个包含 3 个形状为 (x, y), (x, y), (x, z) 的 numpy 二维数组的列表,因此 shape[0] 对于列表中的所有数组都是相同的。在这种情况下,转换为数组失败
ValueError: 无法将输入数组从形状 (x, z) 广播到 形状 (x)
Numpy 尝试创建形状为 (3, x, y) 的数组,而不是保留其类似列表的结构(不同数组的数组)。
如果至少一个shape[0] 与另一个不同,我们就会得到我们想要的,形状为(3,) 的数组数组
我通过将不同类型的元素添加到列表中并使用np.array(list)[:-1] 克服了这个问题。那么,这是一个错误,还是我错过了一些东西(比如 np.array() 参数等)?
一些例子:
>>> import numpy as np
>>> x = np.ones((3,2))
>>> y = np.ones((3,2))
>>> z = np.ones((3,3))
>>> a = np.ones((2,3))
>>> xyz = np.array([x,y,z])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (3,2) into shape (3)
>>> xza = np.array([x,z,a])
[array([[ 1., 1.],
[ 1., 1.],
[ 1., 1.]])
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
array([[ 1., 1., 1.],
[ 1., 1., 1.]])]
>>> xyz2 = np.array([x,y,z,'tmp'])[:-1]
[array([[ 1., 1.],
[ 1., 1.],
[ 1., 1.]])
array([[ 1., 1.],
[ 1., 1.],
[ 1., 1.]])
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])]
【问题讨论】: