In Python, I have a 3 dimensional array A
:
A=np.random.random((3,2,3))
print(A)
Out[6]: [[[0.89565135 0.79502322 0.89015957]
[0.40303084 0.80496231 0.50278239]]
[[0.70610822 0.61269108 0.00470925]
[0.29734101 0.67986295 0.34584381]]
[[0.71822397 0.99326199 0.40949422]
[0.97733739 0.38916931 0.91475145]]]
I would like to select the first element of each submatrix and to make an array from them [0.89565135,0.70610822,0.71822397]
so I tried the following formula : A[:][0][0],A[0][:][0],A[0][0][:]
but they all give me the same result, which is not the one I'm expecting...
A[:][0][0]
Out[7]: array([0.89565135, 0.79502322, 0.89015957])
A[0][:][0]
Out[8]: array([0.89565135, 0.79502322, 0.89015957])
A[0][0][:]
Out[9]: array([0.89565135, 0.79502322, 0.89015957])
What formula can I use to get the right array and how come the above formula give the same result ?
CodePudding user response:
You can do as follows to select for all channel, the first element of the matrix:
A[:, 0, 0]
:
references all channels, 0
the first row and 0
the first column.
Output:
array([0.89565135,0.70610822,0.71822397])
EDIT:
If your are working with nested list
, you can do as follows:
[array[0][0]for array in A]
This shows one of the benefit of numpy
array over python list
as the selection is much more easier (and faster) using numpy
.
CodePudding user response:
Your idea for indexing is a bit flawed here, when you're doing A[:][0][0]
what you're doing is
A[:]
would mean basically the whole matrix, out of which you're specifying out the first index using A[:][0]
which would be
[[0.89565135 0.79502322 0.89015957]
[0.40303084 0.80496231 0.50278239]]
out of which you're further specifying the first index A[:][0][0]
which will give you the first row
[0.89565135 0.79502322 0.89015957]
Following a similar logic you can see that in your second indexing scheme you're effectively doing the same thing. What you need to do is to do
A[0][0][0]
A[1][0][0]
A[2][0][0]
which you can write in short hand
A[:,0,0]