0

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 ?

1
  • 1
    Compare A[:,0,0] to A[0,:,0] and A[0,0,:]. Still identical? Commented Dec 6, 2021 at 11:12

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But still if I write the array directly not as a numpy array : A=[[[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]]] the problem remains. Do you have an idea in that case ?
I added a solution using nested list. However i would advise to perform this operation with numpy as it is much more efficient.
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.