How to sort 3D array's inner 2d arrays with numpy?

Viewed 100

How to sort each 2d array that are in 3d array?

I have an array of shape (10, 1000, 3)

I am trying do a reverse sort by last column in each subarray.

Looping solution:

result = []
for subarr2d in arr3d:
    subarr2d_sorted = subarr2d[subarr2d[:, -1].argsort()][::-1]
    result.append(subarr2d_sorted)

I want to do that in numpy alone? Is it even possible?

1 Answers

You could use numpy.sort and choose the inner axis to sort along.

import numpy as np

result = np.random.randint(20, size=(3, 4, 3))
print(np.sort(result, axis=2))

# outputs
# [[[ 8 11 11]
#   [ 2 11 16]
#   [ 3  7 14]
#   [ 7 12 12]]

#  [[ 8 10 16]
#   [ 0  6 14]
#   [ 0 16 17]
#   [ 0 14 19]]

#  [[ 2  4  5]
#   [ 3  4  4]
#   [ 1  1 11]
#   [ 0  8 17]]]

print(np.sort(result, axis=1))

#outputs
# [[[ 7  2  7]
#   [11  3 11]
#   [12  8 11]
#   [16 12 14]]

#  [[14  6  0]
#   [16  8  0]
#   [17 14  0]
#   [19 16 10]]

#  [[ 2  1  0]
#   [ 3  4  1]
#   [11  4  4]
#   [17  8  5]]]

To get the sorted array in descending order you could use -np.sort(-result, axis=2) and you may also want to check numpy.flip

Related