0

I have a three dimensional array, that I need to sort. I also have a 2 dimensional index that I got with a lexsort that I would like to use for sorting. I cannot find how to apply the index to the array without extra dimensions sprouting up...

import numpy as np

a = np.array([
    [
        [1, 1, 1],
        [0, 1, 2],
        [3, 1, 1],
        [-1, 1, 1],
        [0, 2, 2],
        [1, 2, 2],
    ],[
        [-1, 1, 1],
        [0, 1, 2],
        [-3, 1, 1],
        [1, 1, 1],
        [0, -2, 2],
        [-1, -2, 2],
    ],[
        [-1, 1, 1],
        [-0, 1, -2],
        [-3, 1, 1],
        [1, 1, 1],
        [-0, -2, -2],
        [-1, -2, -2],
    ],
])
sorted_index = np.lexsort((a[:,:,0], a[:,:,1],a[:,:,2]),axis=1)

sorted_index is

[[3 0 2 1 4 5], [2 0 3 5 4 1], [5 4 1 2 0 3]]

the end result should be

a_sorted = np.array([
    [
        [-1, 1, 1],
        [1, 1, 1],
        [3, 1, 1],
        [0, 1, 2],
        [0, 2, 2],
        [1, 2, 2],
    ],[
        [-3, 1, 1],
        [-1, 1, 1],
        [1, 1, 1],
        [-1, -2, 2],
        [0, -2, 2],
        [0, 1, 2],
    ],[
        [-1, -2, -2],
        [0, -2, -2],
        [0, 1, -2],  
        [-3, 1, 1],
        [-1, 1, 1],
        [1, 1, 1],
    ],
])

I tried.

a[sorted_index]
a[sorted_index, :]
a[:, sorted_index]

I am about to loop through the thing, but I would like to do it properly.

1 Answer 1

1

You can use np.take_along_axis

np.take_along_axis(a,sorted_index[...,None],axis=1)

the output is

array([[[-1,  1,  1],
        [ 1,  1,  1],
        [ 3,  1,  1],
        [ 0,  1,  2],
        [ 0,  2,  2],
        [ 1,  2,  2]],

       [[-3,  1,  1],
        [-1,  1,  1],
        [ 1,  1,  1],
        [-1, -2,  2],
        [ 0, -2,  2],
        [ 0,  1,  2]],

       [[-1, -2, -2],
        [ 0, -2, -2],
        [ 0,  1, -2],
        [-3,  1,  1],
        [-1,  1,  1],
        [ 1,  1,  1]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Of course I did a mistake ... I will correct it later in order not to confuse people landing here :D

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.