【发布时间】:2018-08-13 12:45:31
【问题描述】:
我正在尝试创建一个 numpy 数组的数组,每个数组都有不同的维度。 到目前为止,似乎还不错。例如,如果我运行:
np.array([np.zeros((10,3)), np.zeros((11,8))])
结果是:
array([ array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]),
array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]])], dtype=object)
两个矩阵的维度完全不同,生成数组没有任何问题。但是,如果两个矩阵的第一个维度相同,则不再起作用:
np.array([np.zeros((10,3)), np.zeros((10,8))])
Traceback (most recent call last):
File "<ipython-input-123-97301e1424ae>", line 1, in <module>
a=np.array([np.zeros((10,3)), np.zeros((10,8))])
ValueError: could not broadcast input array from shape (10,3) into shape (10)
发生了什么事?
谢谢!
【问题讨论】:
-
我没有很好的解释,除了这是一个错误,但这里有一个解决方法:
L = [np.zeros((10,3)), np.zeros((10,8))]result = np.frompyfunc(L.__getitem__, 1, 1)(range(len(L)))。 -
感谢您的回答!效果很好!!
标签: arrays numpy dimensions valueerror