YouTip LogoYouTip

Numpy Sort Search

NumPy provides multiple sorting methods. These sorting functions implement different sorting algorithms, each characterized by execution speed, worst-case performance, required workspace, and algorithm stability. The following table shows a comparison of three sorting algorithms. | Type | Speed | Worst Case | Workspace | Stability | | --- | --- | --- | --- | --- | | `'quicksort'` | 1 | `O(n^2)` | 0 | No | | `'mergesort'` | 2 | `O(n*log(n))` | ~n/2 | Yes | | `'heapsort'` | 3 | `O(n*log(n))` | 0 | No | ### numpy.sort() The numpy.sort() function returns a sorted copy of the input array. The function format is as follows: numpy.sort(a, axis, kind, order) Parameter description: * a: The array to be sorted. * axis: The axis along which to sort the array. If not provided, the array is flattened and sorted along the last axis. axis=0 sorts along columns, axis=1 sorts along rows. * kind: Default is 'quicksort'. * order: If the array contains fields, this specifies the field to sort by. ## Example import numpy as np a = np.array([[3,7],[9,1]])print('Our array is:')print(a)print('n')print('Calling sort() function:')print(np.sort(a))print('n')print('Sorting along columns:')print(np.sort(a, axis = 0))print('n')dt = np.dtype([('name', 'S10'),('age', int)])a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt)print('Our array is:')print(a)print('n')print('Sorting by name:')print(np.sort(a, order = 'name')) The output is: Our array is:[ ]Calling sort() function:[ ]Sorting along columns:[ ]Our array is:[(b'raju', 21) (b'anil', 25) (b'ravi', 17) (b'amar', 27)]Sorting by name:[(b'amar', 27) (b'anil', 25) (b'raju', 21) (b'ravi', 17)] ### numpy.argsort() The numpy.argsort() function returns the indices that would sort an array from smallest to largest. ## Example import numpy as np x = np.array([3, 1, 2])print('Our array is:')print(x)print('n')print('Calling argsort() function on x:')y = np.argsort(x)print(y)print('n')print('Reconstructing the original array in sorted order:')print(x)print('n')print('Reconstructing the original array using a loop:')for i in y: print(x, end="") The output is: Our array is:Calling argsort() function on x:Reconstructing the original array in sorted order:Reconstructing the original array using a loop:1 2 3 ### numpy.lexsort() numpy.lexsort() is used to sort multiple sequences. Think of it as sorting a spreadsheet where each column represents a sequence, and sorting prioritizes the later columns. Here is an application scenario: In a primary school to middle school entrance exam, key classes admit students based on total score. When total scores are the same, students with higher math scores are admitted first. When both total and math scores are the same, English scores are used for admission... Here, the total score is in the last column of the spreadsheet, math scores in the second-to-last column, and English scores in the third-to-last column. ## Example import numpy as np nm = ('raju','anil','ravi','amar')dv = ('f.y.', 's.y.', 's.y.', 'f.y.')ind = np.lexsort((dv,nm))print('Calling lexsort() function:')print(ind)print('n')print('Using this index to get the sorted data:')print([nm + ", " + dvfor i in ind]) The output is: Calling lexsort() function:Using this index to get the sorted data:['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.'] The tuple passed to np.lexsort is sorted first by nm, with the order: amar, anil, raju, ravi. Therefore, the sorting result is . ### msort, sort_complex, partition, argpartition | Function | Description | | --- | --- | | msort(a) | Sorts the array along the first axis and returns a sorted copy. np.msort(a) is equivalent to np.sort(a, axis=0). | | sort_complex(a) | Sorts complex numbers by real part first, then by imaginary part. | | partition(a, kth[, axis, kind, order]) | Partitions the array around the kth element. | | argpartition(a, kth[, axis, kind, order]) | Partitions the array along the specified axis using the algorithm specified by the kind keyword. | Sorting complex numbers: >>> import numpy as np >>> np.sort_complex([5, 3, 6, 2, 1]) array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])>>>>>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j]) partition() partition sorting: >>> a = np.array([3, 4, 2, 1])>>> np.partition(a, 3) # All elements in array a (including duplicates) are arranged from smallest to largest. 3 indicates the element at index 3 in the sorted array. Elements smaller than this number are placed before it, and elements larger than this number are placed after it. array([2, 1, 3, 4])>>>>>> np.partition(a, (1, 3)) # Elements less than 1 are in front, greater than 3 are at the end, and those between 1 and 3 are in the middle. array([1, 2, 3, 4]) Find the 3rd smallest (index=2) and 2nd largest (index=-2) values in the array: >>> arr = np.array([46, 57, 23, 39, 1, 10, 0, 120])>>> arr[np.argpartition(arr, 2)]10>>> arr[np.argpartition(arr, -2)]57 Find the 3rd and 4th smallest values simultaneously. Note that here, [2,3] sorts the 3rd and 4th smallest values at the same time, which can then be accessed via indices and respectively. >>> arr[np.argpartition(arr, [2,3])]10>>> arr[np.argpartition(arr, [2,3])]23 ### numpy.argmax() and numpy.argmin() The numpy.argmax() and numpy.argmin() functions return the indices of the maximum and minimum elements along a given axis, respectively. ## Example import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]])print('Our array is:')print(a)print('n')print('Calling argmax() function:')print(np.argmax(a))print('n')print('Flattening the array:')print(a.flatten())print('n')print('Indices of maximum values along axis 0:')maxindex = np.argmax(a, axis = 0)print(maxindex)print('n')print('Indices of maximum values along axis 1:')maxindex = np.argmax(a, axis = 1)print(maxindex)print('n')print('Calling argmin() function:')minindex = np.argmin(a)print(minindex)print('n')print('Minimum value in the flattened array:')print(a.flatten())print('n')print('Indices of minimum values along axis 0:')minindex = np.argmin(a, axis = 0)print(minindex)print('n')print('Indices of minimum values along axis 1:')minindex = np.argmin(a, axis = 1)print(minindex) The output is: Our array is:[ ]Calling argmax() function:7Flattening the array:Indices of maximum values along axis 0:Indices of maximum values along axis 1:Calling argmin() function:5Minimum value in the flattened array:10Indices of minimum values along axis 0:Indices of minimum values along axis 1: ### numpy.nonzero() The numpy.nonzero() function returns the indices of non-zero elements in the input array. ## Example import numpy as np a = np.array([[30,40,0],[0,20,10],[50,0,60]])print('Our array is:')print(a)print('n')print('Calling nonzero() function:')print(np.nonzero(a)) The output is: Our array is:[ ]Calling nonzero() function:(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2])) ### numpy.where() The numpy.where() function returns the indices of elements in the input array that satisfy a given condition. ## Example import numpy as np x = np.arange(9.).reshape(3, 3)print('Our array is:')print(x)print('Indices of elements greater than 3:')y = np.where(x>3)print(y)print('Using these indices to get the elements that meet the condition:')print(x) The output is: Our array is:[[0. 1. 2.] [3. 4. 5.] [6. 7. 8.]]Indices of elements greater than 3:(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))Using these indices to get the elements that meet the condition:[4. 5. 6. 7. 8.] ### numpy.extract() The numpy.extract() function extracts elements from an array based on a condition and returns the elements that satisfy the condition. ## Example import numpy as np x = np.arange(9.).reshape(3, 3)print('Our array is:')print(x)condition = np.mod(x,2) == 0 print('Condition values for each element:')print(condition)print('Extracting elements using the condition:')print(np.extract(condition, x)) The output is: Our array is:[[0. 1. 2.] [3. 4. 5.] [6. 7. 8.]]Condition values for each element:[ ]Extracting elements using the condition:[0. 2. 4. 6. 8.]
← Numpy Copies And ViewsNumpy Arithmetic Operations β†’