python3 numpy ndarray 没有一致的维度。遇到具有形状属性的奇怪行为

python3 numpy ndarray does not have consistant dimentions. Encountered odd behavor with shape atribute

我在 python 3 中使用 numpy 包。 首先,这里有一些代码显示了我在使用 ndarray 形状属性时遇到的奇怪行为。

threeDndarray = np.ndarray(shape=(2,5,2)) #3d ndarray to showcase behavor 
print(threeDndarray.shape)
**output:** (2, 5, 2)
print(threeDndarray[:][:][:].shape) 
**output:** (2, 5, 2)
#now the odd behavor
print(threeDndarray[:][1][:].shape) #expected (2,2) 
**output:** (5, 2) 
print(threeDndarray[:][:][1].shape)
**output:** (5, 2)
print(threeDndarray[1][:][:].shape)
**output:** (5, 2)

我相信这种奇怪的 .shape 行为与我遇到的问题有关。 我想将五个独立的 2x2 矩阵的值存储在一个维度为 (2,5,2) 的 3dndarray 中。我无法执行操作 my3dArray[:][i][:] = my2dMatrix,而不会收到与维度不匹配相关的错误。

具体错误是

ValueError: could not broadcast input array from shape (2,2) into shape (5,2)

我不明白为什么会出现此错误或为什么形状属性有如此奇怪的行为。

您没有正确使用 numpy 索引。

array[1]
array[:][1]
array[:][:][1]

都是相同的操作(查看数组,然后访问第一维的索引 1),因为 (array[:] == array).all()True。我想你的意思是

threeDndarray[1, :, :].shape
threeDndarray[:, 1, :].shape
threeDndarray[:, :, 1].shape