1

let's assume I have an array of form

a = [ 
  [ [12, 4, 2, 5] , [10, 12, 4, 2], [2, 2, 10, 2], [7, 10, 3 ,2] ],
  [ [13, 23, 4, 5] , [10, 12, 4, 2], [2, 2, 12, 1], [7, 10, 3 ,2] ],
  [ [4, 4, 2, 5] , [10, 12, 4, 2], [2, 2, 3, 2], [7, 10, 3 ,2] ], 
] 

I want to sort by the first column of each element, so the first entry of a would read:

[ [2, 2, 10, 2], [7, 10, 3 ,2], [10, 12, 4, 2], [12, 4, 2, 5] ]

I've found a solution that looks like a[a[:,1].argsort()] and tried a for loop over the first index like:

for i in range(0,4):
  a[i,...] = a[a[i,0,:].argsort()]

or

for i in range(0,4):
  a[i,...] = a[i, a[i,0,:].argsort()]

This doesn't work tho. I really can't get my head around this problem.

3 Answers 3

2

You can use argsort of the array indexed along the first columns, and expanding dims appropriately, and then np.take_along_axis:

ixs = a[...,0].argsort(1)[...,None]
np.take_along_axis(a, ixs, 1)

array([[[ 2,  2, 10,  2],
        [ 7, 10,  3,  2],
        [10, 12,  4,  2],
        [12,  4,  2,  5]],

       [[ 2,  2, 12,  1],
        [ 7, 10,  3,  2],
        [10, 12,  4,  2],
        [13, 23,  4,  5]],

       [[ 2,  2,  3,  2],
        [ 4,  4,  2,  5],
        [ 7, 10,  3,  2],
        [10, 12,  4,  2]]])
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

sorted_array = [sorted(x, key=lambda y: y[0]) for x in a]

How does this work?

  • first we use list comprehension to map the array a into a new one, performing an operation on each element (e.g. [x + 1 for x in my_numbers])

  • The operation we perform on each element of a is to use sorted. This returns a copy of an array, sorted by comparing whatever value is returned by key.

  • key must be a function that returns a 'sortable' value. Here, we're using a lambda to create a one-line function that returns the first item from the array passed to it. This ensures that we sort based on the first column of each element of a.

2 Comments

This solution didn't let me plot the array with matplot anymore.
Well, in fairness, you didn't mention you were using matplot ¯\_(ツ)_/¯
1

If you don’t want to use lambda method try this one:

def select(item):
  return item[0]


s_array=[]
for i in a:
  s_array.append(sorted(i, key=select))

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.