这是一个代码。我列出了包含两个形状不同的ndarray的列表。
d = []
a = np.arange(183).reshape(3,61)
b = np.arange(51).reshape(3,17)
d = [a,b]
np.array(d)
错误如下。
File "C:\Program Files\JetBrains\PyCharm 2019.1.1\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "D:/dev/workspace/rl/test/npcopy.py", line 10, in <module>
np.array(d)
ValueError: could not broadcast input array from shape (3,61) into shape (3)
np.copy()在两个ndarray的第一个shpae不同时起作用。但是如果没有,它就不能像上面那样工作。
如果我按以下方式更改此代码,
import numpy as np
d = []
a = np.arange(183).reshape(4, 61)
b = np.arange(51).reshape(3, 17)
d = [a,b]
np.array(d)
有效!!好奇怪!
答案 0 :(得分:3)
因为矩阵的维数不同
> a = np.arange(183).reshape(3,61) b = np.arange(51).reshape(3,17)
> d=[np.array(a),np.array(b)]
> print(d) for output
>
> or d=[a,b]
> np.concatenate(d, axis=1)
答案 1 :(得分:1)
当您尝试使用数组制作数组时,可能会出现三种结果:
如果数组具有相同的形状,则结果是一维数组:
In [295]: np.array((np.zeros((2,3),int),np.ones((2,3),int)))
Out[295]:
array([[[0, 0, 0],
[0, 0, 0]],
[[1, 1, 1],
[1, 1, 1]]])
In [296]: _.shape
Out[296]: (2, 2, 3)
如果数组的形状不同,则结果可能是对象dtype数组(类似于list
):
In [298]: np.array((np.zeros((2,3),int),np.ones((3,3),int)))
Out[298]:
array([array([[0, 0, 0],
[0, 0, 0]]),
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])], dtype=object) # shape (2,)
但是对于某些形状组合,结果是一个错误:
In [301]: np.array((np.zeros((2,3),int),np.ones((2,4),int)))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-301-d67e6685581d> in <module>
----> 1 np.array((np.zeros((2,3),int),np.ones((2,4),int)))
ValueError: could not broadcast input array from shape (2,3) into shape (2)
在错误情况下,第一个尺寸匹配,就像在第一种情况下一样。
有时要创建一个对象数组,必须先从一个“空”数组开始,然后填充它。这比np.array(...)
方法更可靠。
In [303]: arr = np.empty(2, object)
In [304]: arr[:] = np.zeros((2,3),int),np.ones((2,4),int)
In [305]: arr
Out[305]:
array([array([[0, 0, 0],
[0, 0, 0]]),
array([[1, 1, 1, 1],
[1, 1, 1, 1]])], dtype=object)
In [306]: arr[:] = np.zeros((2,3),int),np.ones((2,3),int)
In [307]: arr
Out[307]:
array([array([[0, 0, 0],
[0, 0, 0]]),
array([[1, 1, 1],
[1, 1, 1]])], dtype=object)
答案 2 :(得分:0)
我选择使用copy.deepcopy()而不是np.copy()。即使列表中两个项目的第一个形状相同也可以使用。