JohnDoe122
JohnDoe122

Reputation: 688

How to sort groups of numbers simultaneously

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!

Upvotes: 1

Views: 398

Answers (2)

RoyM
RoyM

Reputation: 746

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])

Upvotes: 1

hiro protagonist
hiro protagonist

Reputation: 46901

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.

Upvotes: 3

Related Questions