NumPy Array Sort

Sorting arrays in NumPy allows you to organize data in ascending or descending order. Sorting is available for both 1D and multi-dimensional arrays, making it useful for tasks like ranking population densities or temperatures.

Key Topics

Sorting 1D Arrays

The sort() function sorts a 1D array in ascending order by default.

Example

# Sorting a 1D array
import numpy as np

temperatures_chennai = np.array([32, 35, 30, 33, 31])
temperatures_chennai.sort()

print("Sorted temperatures in Chennai:", temperatures_chennai)

Output

Sorted temperatures in Chennai: [30 31 32 33 35]

Explanation: The sort() method arranges the array elements in ascending order. For 1D arrays, the method operates on the entire array.

Sorting 2D Arrays

For 2D arrays, you can sort along a specific axis. By default, sorting is row-wise (axis=1).

Example

# Sorting a 2D array
rainfall_data = np.array([[200, 100, 300], [150, 250, 50]])
rainfall_data.sort(axis=1)

print("Row-wise sorted rainfall data:")
print(rainfall_data)

Output

Row-wise sorted rainfall data:
[[100 200 300]
[ 50 150 250]]

Explanation: Setting axis=1 sorts each row individually. Similarly, you can set axis=0 to sort columns.

Key Takeaways

  • Sorting 1D Arrays: Use sort() to arrange array elements in ascending order.
  • Sorting 2D Arrays: Specify the axis to sort rows or columns.
  • In-Place Sorting: The sort() function modifies the original array.
  • Example Use: Organize temperatures or rainfall data for easier analysis.