[英]Slicing 3d Arrays
I want to slice 3D arrays in a way to only print the last element of each row in the 2nd array.我想切片 3D arrays 以仅打印第二个数组中每行的最后一个元素。
In my 3D Array:在我的 3D 阵列中:
np.random.seed(42)
M = np.random.randint(10, size=(2,2,10))
print(M)
I tried accessing the last elements of the 2nd Array in a way like this:我尝试以如下方式访问第二个数组的最后一个元素:
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
I understand the first print() method like:我了解第一个 print() 方法,例如:
1: # chose the second array 1: # 选择第二个数组
: # chose all rows of the 2nd array : # 选择第二个数组的所有行
:2 # chose every second index of the row and print it :2 # 选择行的每个第二个索引并打印它
strangely it prints the whole array which confuses me.奇怪的是,它打印了整个数组,这让我感到困惑。 The second print() method i was hoping to at least print the 2nd index alone but I get that error message.
第二个 print() 方法我希望至少单独打印第二个索引,但我收到了该错误消息。
So I tried around more and came up with that code:所以我尝试了更多并想出了那个代码:
print(M[1:,0:,::2])
It gives me the result I want, but I cannot read the code.它给了我想要的结果,但我无法阅读代码。 I understand
我明白
1: ## which chooses the 2nd array 1: ## 选择第二个数组
but,0:,::2 is confusing me.但是,0:,::2 让我很困惑。 ::2 is chosing every 2nd index I guess but I still don't understand when I can make ':' and when not.
::2 正在选择我猜的每个第二个索引,但我仍然不明白我什么时候可以制作 ':' 什么时候不能。 Or what is the meaning of ',' in the slicing process.
或者切片过程中的“,”是什么意思。
In numpy,the operator works as follows:- [start_index:end_index:step]
.在 numpy 中,操作符的工作方式如下:-
[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]
).这意味着当您索引 M[1:,0:,::2] 时,您实际索引的是从第一个维度的第一个索引(
[1:]
)开始的所有内容,然后是从第二个维度开始的所有内容( [0:]
),最后是步长为 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. ,
用于分隔尺寸,所以我假设你真正想要做的是M[:,1,-1]
来获取每个第二个数组的最后一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.