简体   繁体   中英

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.

In my 3D Array:

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:
1: # chose the second array
: # chose all rows of the 2nd array
:2 # chose every second index of the row and print it

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.

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
but,0:,::2 is confusing me. ::2 is chosing every 2nd index I guess but I still don't understand when I can make ':' and when not. Or what is the meaning of ',' in the slicing process.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM