2

For a 2d array, a, we can sort using

a = a[a[:, 0].argsort]

if we want to sort by column 0. How to do a similar thing for a 3d matrix? If we have


a = [[[ 1.,  2., 10.],
         [ 4.,  5.,  6.],
         [ 2.,  3.,  4.]],

        [[ 2.,  3.,  4.],
         [ 4.,  5.,  6.],
         [ 1.,  2.,  3.]],

        [[ 1.,  2.,  3.],
         [ 4.,  5.,  6.],
         [ 2.,  3.,  4.]]]

And we want to sort according to the first column of each element of the 3d matrix?

5
  • a = a[a[:,:,0].argsort()] ?? Commented Feb 12, 2020 at 22:09
  • Gives a (3, 3, 3, 3) array Commented Feb 12, 2020 at 22:15
  • what's your expected output? Commented Feb 12, 2020 at 22:23
  • A (3, 3, 3) sorted array. Sorted by the first column of each element. Commented Feb 14, 2020 at 21:45
  • We sort an array by element, but in your case your element is a whole column, we can't make comparisons like [1,2,3] > [1,3,5], what you can do is compare the first element of each column, the l1 or l2 norms, max value, etc. Commented Feb 15, 2020 at 14:11

1 Answer 1

1

I hope this can help:

COL = 0
DIM0 = 3
a[:, a[:, :, COL].argsort()][np.diag_indices(DIM0)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. Explaining what is happening in it would probably make it more helpful to the asker.

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.