Tuesday, August 11, 2020

Array Sorting

 Array Sorting


You can even do a sort on an array of Booleans, and all the False values will appear before even the first of the Trues.

The original array is unchanged and .sort() makes a copy so be prepared to accept a return value.


.sort(a, axis, kind, order) as a numpy method


a: array to be sorted

axis: default is -1, which is the last axis and is always the fastest to sort on. Specifying  'None' flattens the 2-D array before sorting.

kind: your choice of sorting algorithm.


order: a complex argument that depends on the structured array and definitions in a list of the rank of non-numerical fields.


See the official page for numpy.sort() to learn more and get all your many parameter choices.


import numpy as np


a = np.array([[3, 4, -2],[2, 11, 8]])


b = np.sort(a, axis=-1, kind='heapsort')    

# sort along the last axis

print(b)

c = np.sort(a, axis=None)   # sort the flattened array

print(c)

d = np.sort(a, axis=0)      # sort along the first axis

print(d)


# results in:

#a

[[-2  3  4]

 [ 2  8 11]]


#b

[-2  2  3  4  8 11]


#c

[[ 2  4 -2]

 [ 3 11  8]]


If you don't want to make a copy by sorting, use the sort-in-place method numpy.ndarray.sort().


import numpy as np

unordered_array = np.array([13, 17, -9, 101])

newarray = np.ndarray.sort(unordered_array)

print(unordered_array)

print(newarray)

# results in, with no array returned from ndarray.sort():


[ -9  13  17 101]

None








No comments:

Post a Comment