0

I have a 3D multidimensional arr = (x, y, z) shaped numpy array. Shape = (10000, 99, 2) in this example.

I.e. we have 10000 instances of 99 x 2 two dimensional arrays.

I would like to sort the whole array by the values in the z index i.e. ranking according to the 99 variables across rows in each column, across each instance.

Is there an easy way to do this using vectorisation? I'm aware I could loop over 10000 iterations, sorting the 2d array like below and combining to a 3d output.

np.unique(arr[:,0], return_inverse=True)
np.unique(arr[:,1], return_inverse=True)

Given I have 10000 outer instances, I am however interested in avoiding loops and sorting all 10000 values in a more efficient manner.

1 Answer 1

1

I am not sure if I understand the z score completely, but you can try:

np.sort(arr,axis=1)

An example 3-d input:

import numpy as np
rng_seed = 42  # control reproducibility
rng = np.random.RandomState(rng_seed)
arr=rng.randint(0,40,20).reshape(2,5,2)

The input looks like:

[[[38 28]
  [14  7]
  [20 38]
  [18 22]
  [10 10]]

 [[23 35]
  [39 23]
  [ 2 21]
  [ 1 23]
  [29 37]]]

Applying:

arr1=np.sort(arr,axis=1)
print (arr1)

Gives you the sorted array based on column within each instance:

[[[10  7]
  [14 10]
  [18 22]
  [20 28]
  [38 38]]

 [[ 1 21]
  [ 2 23]
  [23 23]
  [29 35]
  [39 37]]]

If you want the rank of each value instead, try:

arr_rank = arr.argsort(axis=1)
print (arr_rank)

The output is:

[[[4 1]
  [1 4]
  [3 3]
  [2 0]
  [0 2]]

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

2 Comments

thank you, this does indeed sort the values as intended. This may be worth a separate post but is there a similar method for finding the ranked order of each value in its original position in the 3d across the column in each instance.
Do you want to know the rank of each value? Then, in your case, the output will contains integers 0-98 only? If that is the case check my updated answer.

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.