1

I have a 3 dimensional numpy array of dimensions 333*333*52

I have a 333 element lists of indices ranging from 0-332 eg [4 12 332 0 ...] that I wish to use to rearrange the first two dimensions of the 3d array

In matlab I would do:

rearranged_array = original_array(new_order, new_order, :)

But this approach does not work with numpy:

rearranged_array = original_array[new_order, new_order, :]

Produces a 333*52 array

While:

rearranged_array = original_array[new_order][new_order, :]

Does not get things in the right order

Edit:

This seems to work:

rearranged_array = original_array[new_order, :][:, new_order]

This seems a lot less intuitive to me than the matlab method - are there any better ways?

1 Answer 1

2

Your third one

rearranged_array = original_array[new_order][new_order, :]

is just doing the same operation twice.

You want

rearranged_array = original_array[new_order][:, new_order]

The reason your first solution doesn't work is because numpy only does the rearrangement if the index passed is a list or array, but if you pass new_order, new_order, that is a tuple.

Another solution is to do

 rearranged_array = original_array[np.row_stack((new_order, new_order))]

nb. you keep doing things like a[x, y, :] and a[x, :]. Trailing : are superfluous. a[x, y] and a[x] respectively do exactly the same thing.

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

1 Comment

I wouldn't say trailing : are superfluous. The code doesn't need them because they will be inferred. But humans often need them to keep dimensions straight.

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.