1

Is there a method in numpy that allows me to sort these 3d vectors in ascending order?

For example; I have the following input array and I'd like the following output:

input_arr = np.array( [
    [[255,0,3],
    [255,4,100],
    [255,2,3],
    [255,3,3],
    [0,1,3],
    ] ]
, dtype='uint8')

# Sort input_arr to produce the below

output_arr = np.array( [
    [[0,1,3],
    [255,0,3],
    [255,2,3],
    [255,3,3],
    [255,4,100],
    ] ]
, dtype='uint8')

I have tried the below but it does not produce the result I wanted above. Instead it produces the below.

output_arr2 = np.sort( input_arr, axis=0)

# Results in the below
[[[255   0   3]
 [255   4 100]
 [255   2   3]
 [255   3   3]
 [  0   1   3]]]
sazr
  • 24,984
  • 66
  • 194
  • 362
  • Your array is (1 5,3) shape. Do you understand why the `axis=0` doesn't change anything? You should be explicit about your sorting criteria; we shouldn't have to deduce it from your example. If you don't like any of the 'duplicates' answer, it's probably because you weren't clear. – hpaulj Apr 01 '23 at 16:02
  • Since this closed, I'll just post a possbiel answer without explanation: `input_arr[:,np.argsort(np.sum(input_arr,axis=2)),:]` – hpaulj Apr 01 '23 at 16:03

1 Answers1

0
output_arr = np.asarray(list(map(lambda x: sorted(
    x, key=lambda rows: tuple(rows)), input_arr)), dtype='uint8')

This code takes a 2-dimensional input array input_arr, sorts the rows of each 2-dimensional sub-array in ascending order based on the values in the row, and stores the sorted arrays in a new 2-dimensional NumPy array output_arr.

Here's a step-by-step breakdown of what the code does:

  1. lambda rows: tuple(rows) creates a lambda function that takes a row and converts it to a tuple. This is used as the key function for the sorted() function below.

  2. lambda x: sorted(x, key=lambda rows: tuple(rows)) creates a lambda function that takes a sub-array x, and sorts its rows in ascending order based on the values in each row, using the lambda function created in step 1 as the key function for the sort.

  3. map(lambda x: sorted(x, key=lambda rows: tuple(rows)), input_arr) applies the lambda function from step 2 to each sub-array in input_arr, resulting in an iterable of sorted sub-arrays.

  4. list() converts the iterable from step 3 to a list.

  5. np.asarray() converts the list from step 4 to a NumPy array, with the data type specified as uint8.

So in summary, this code takes a 2-dimensional input array, sorts each sub-array in ascending order based on the values in each row, and returns a new 2-dimensional NumPy array with the sorted sub-arrays.

l3on13
  • 11
  • 3