NumPy Array Sort
NumPy provides several functions to sort arrays. This chapter covers how to sort elements within arrays, sort along different axes, and handle structured arrays.
Basic Sorting
To sort an array, you can use the numpy.sort()
function, which returns a sorted copy of the array.
Example: Basic Sorting
import numpy as np
arr = np.array([3, 1, 2, 5, 4])
# Sort the array
sorted_arr = np.sort(arr)
print(sorted_arr)
This code sorts the elements of the array in ascending order.
Sorting Along an Axis
When dealing with multi-dimensional arrays, you can sort along a specific axis using the axis
parameter.
Example: Sorting Along an Axis
import numpy as np
arr = np.array([[3, 2, 1], [6, 5, 4]])
# Sort along the first axis (rows)
sorted_arr = np.sort(arr, axis=0)
print(sorted_arr)
# Sort along the second axis (columns)
sorted_arr = np.sort(arr, axis=1)
print(sorted_arr)
This code sorts the array along the specified axis.
In-Place Sorting
To sort an array in-place, you can use the sort()
method of the array object.
Example: In-Place Sorting
import numpy as np
arr = np.array([3, 1, 2, 5, 4])
# Sort the array in-place
arr.sort()
print(arr)
This code sorts the array in-place, modifying the original array.
Structured Arrays
NumPy allows you to create structured arrays with named fields and sort them based on specific fields.
Example: Sorting Structured Arrays
import numpy as np
# Create a structured array
arr = np.array([(1, 'B'), (3, 'A'), (2, 'C')],
dtype=[('number', 'i4'), ('letter', 'U1')])
# Sort the array by the 'number' field
sorted_arr = np.sort(arr, order='number')
print(sorted_arr)
This code sorts the structured array based on the specified field.
Conclusion
NumPy provides flexible and efficient sorting functions that allow you to sort arrays in various ways. Understanding these functions helps in managing and organizing data effectively.