Preserving the dimensions of a slice from a Numpy 3d array

倖福魔咒の 提交于 2019-11-30 08:30:00

问题


I have a 3d array, a, of shape say a.shape = (10, 10, 10)

When slicing, the dimensions are squeezed automatically i.e.

a[:,:,5].shape = (10, 10)

I'd like to preserve the number of dimensions but also ensure that the dimension that was squeezed is the one that shows 1 i.e.

a[:,:,5].shape = (10, 10, 1)

I have thought of re-casting the array and passing ndmin but that just adds the extra dimensions to the start of the shape tuple regardless of where the slice came from in the array a.


回答1:


a[:,:,[5]].shape
# (10,10,1)

a[:,:,5] is an example of basic slicing.

a[:,:,[5]] is an example of integer array indexing -- combined with basic slicing. When using integer array indexing the resultant shape is always "identical to the (broadcast) indexing array shapes". Since [5] (as an array) has shape (1,), a[:,:,[5]] ends up having shape (10,10,1).



来源:https://stackoverflow.com/questions/2640147/preserving-the-dimensions-of-a-slice-from-a-numpy-3d-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!