首页 > 解决方案 > 切片 3d 数组

问题描述

我想以仅打印第二个数组中每一行的最后一个元素的方式对 3D 数组进行切片。

在我的 3D 阵列中:

np.random.seed(42)
M = np.random.randint(10, size=(2,2,10))
print(M)

我尝试以如下方式访问第二个数组的最后一个元素:

print(M[1::2])   ## which just prints me the whole 2nd Array
print(M[1::,2])  ## which gives me an error of index 2 being out of bounds

我理解第一个 print() 方法,例如:
1: # 选择第二个数组
: # 选择第二个数组的所有行
:2 # 选择行的每个第二个索引并打印它

奇怪的是,它打印了整个数组,这让我感到困惑。第二个 print() 方法我希望至少单独打印第二个索引,但我收到了该错误消息。

所以我尝试了更多并想出了那个代码:

print(M[1:,0:,::2])

它给了我想要的结果,但我无法阅读代码。我理解
1: ## 选择第二个数组
但是 ,0:,::2 让我感到困惑。::2 正在选择我猜的每个第二个索引,但我仍然不明白我什么时候可以制作 ':' 什么时候不能。或者切片过程中的“,”是什么意思。

标签: pythonarraysslice

解决方案


In numpy,the operator works as follows :- [start_index:end_index:step].

This means that when you index M[1:,0:,::2] what you are actually indexing is everything from the first index of the first dimension([1:]), then everything from the start of the second dimension([0:]), and finally every element with a step of 2 ([::2]).

The , is used to seperate the dimensions so I assume what you actually want to do is M[:,1,-1] to get the last element of every 2nd array.


推荐阅读