2

I have a large 3D array A with shape (N, M, L).

I have a list of coordinates of columns I want to access stored in a 2D array B:

[[i1 j1]
 [i2 j2]
 [i3 j3]
 ....   ]

I have something that works OK but involves looping over B and accessing A multiple times. Is there a way to avoid this using slicing or another method?

My code so far:

data_out = []
for p in B:
    i, j = p
    col = A[:, i, j]
    data_out.append(col)

1 Answer 1

2

Use fancy indexing:

A[(slice(None), *B.T)].T

The explicit parentheses are necessary to use star expansion, which means that you have to write out : explicitly as slice(None). You can also do

A[:, B[:, 0], B[:, 1]].T
Sign up to request clarification or add additional context in comments.

1 Comment

@Divakar. Fixed. I forgot that B was being split into 1D and relied on its shape :)

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.