1

Hello I have a numpy array, and I want to sort it based on the elements with index modulo 3, such that each group of 3 consecutive elements (starting from the one module 3 stay together. For example for the array [7,3.4,5.6, 4,5.5,1.2, 12,4.4,4.5] the numbers I want to put in order are 7, 4, 12, and keep the 2 numbers coming right after them in the same order. Hence what I want to get in the end is this array: [4,5.5,1.2, 7,3.4,5.6, 12,4.4,4.5]. I can do it with some for loops, but is there a fast, numpy built-in function that I can take advantage of? Thank you!

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
JohnDoe122
  • 638
  • 9
  • 23

2 Answers2

3

this is a variant:

import numpy as np

a = np.array([7, 3.4, 5.6, 4, 5.5, 1.2, 12, 4.4, 4.5])
a = a.reshape((3, 3))
a = a[a[:, 0].argsort()].flatten()
print(a)  # [  4.    5.5   1.2   7.    3.4   5.6  12.    4.4   4.5]

i rehsape the array to shape (3, 3) and then sort the first column only (as described here) and flatten it again.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Thanks a lot! Can this be used for the case of high dimension arrays, too i.e. for example a = np.array([[7, 3.4, 5.6, 4, 5.5, 1.2, 12, 4.4, 4.5],[7, 3.4, 5.6, 5, 5.5, 1.2, 12, 4.4, 4.5]])? Where the sorting would be done for each subgroup individually (in this case 2 different sortings). – JohnDoe122 Oct 30 '19 at 07:09
  • i suppose that should work; `a[:, col_nr]` selects the the column number you want sorted... best just try it! – hiro protagonist Oct 30 '19 at 07:13
1

You'll achieve this using these np-functions in sequence. You can of course chain them all at once.

import numpy as np
a = np.array([7,3.4,5.6, 4,5.5,1.2, 12,4.4,4.5])
a = np.array_split(a, 3)
a.sort(key=lambda x: x[0])
a = np.array(a).flatten()

Out: array([ 4. , 5.5, 1.2, 7. , 3.4, 5.6, 12. , 4.4, 4.5])

RoyM
  • 735
  • 3
  • 14