Python

πŸ“˜ Chapter 9: Sorting and Searching in NumPy β€” Finding Order in Chaos

🧠 β€œIn the world of data, knowing where and how to look is as important as having the data.”

Welcome to Chapter 9 of our journey through the power-packed world of NumPy.

By now, you know how to create arrays, reshape them, filter using Boolean logic, and manipulate data like a pro. But when your datasets grow in size, so does the need for structure and searchability.

That’s where sorting and searching come into play.
In this chapter, you’ll learn how to:

  • Sort arrays efficiently

  • Find the positions of elements

  • Use functions like sort(), argsort(), searchsorted(), and nonzero()

These are key skills in:

  • Ranking data

  • Locating items

  • Preparing for binary search

  • Building recommendation systems

Let’s get started! πŸš€


πŸ” 1. Sorting with np.sort()

πŸ”Έ Basic Usage

import numpy as np

arr = np.array([50, 10, 30, 20])
sorted_arr = np.sort(arr)
print("Sorted array:", sorted_arr)

Output:

[10 20 30 50]

🎯 np.sort() returns a sorted copy β€” your original array stays unchanged.


🧱 2. Sorting Multi-Dimensional Arrays

You can sort row-wise or column-wise using the axis parameter.

matrix = np.array([[3, 1, 2], [9, 6, 8]])
print("Sort each row:\n", np.sort(matrix, axis=1))
print("Sort each column:\n", np.sort(matrix, axis=0))

 

Output:

[[1 2 3]
 [6 8 9]]

 


πŸ” 3. In-Place Sorting with .sort()

arr = np.array([40, 10, 20])
arr.sort()  # modifies in place
print(arr)  # [10 20 40

 


🧠 4. Getting Sort Indices with np.argsort()

argsort() returns the indices that would sort an array.

arr = np.array([40, 10, 30])
indices = np.argsort(arr)
print("Sort indices:", indices)
print("Sorted by indices:", arr[indices])

Output:

[1 2 0]
[10 30 40]

βœ… This is super useful when you want to sort related arrays based on one array’s values.


🎯 5. Finding Elements: np.searchsorted()

Used to find the index where an element should be inserted to maintain order.

πŸ“Œ Example:

arr = np.array([10, 20, 30, 40])
pos = np.searchsorted(arr, 25)
print("Insert at position:", pos)  # Output: 2

You can also insert multiple values:

print(np.searchsorted(arr, [5, 35]))  # Output: [0 3]

πŸ“ 6. Finding Specific Elements with np.where()

You can use where() to locate indices of matching conditions.

arr = np.array([10, 20, 30, 40])
index = np.where(arr == 30)
print("Index of 30:", index)

Output:

(array([2]),)

You can also find multiple matches:

arr = np.array([10, 20, 20, 30])
print(np.where(arr == 20))  # Output: (array([1, 2]),)


🧩 7. Finding Non-Zero Values: np.nonzero()

This function returns the indices of non-zero elements in the array.

arr = np.array([0, 10, 0, 20])
nonzero_indices = np.nonzero(arr)
print("Non-zero at:", nonzero_indices)

Output:

(array([1, 3]),)

Useful in:

  • Sparse matrices

  • Filtering

  • Counting actual data points


πŸ§ͺ Real-World Use Cases

Task Function
Sort sales data np.sort()
Rank test scores np.argsort()
Find top N performers argsort() + slicing
Insert item in order searchsorted()
Locate missing/active values where(), nonzero()

πŸ“¦ BONUS: Sort by Another Array (Key-Based Sort)

Let’s say you have names and scores:

names = np.array(['Alice', 'Bob', 'Charlie'])
scores = np.array([88, 95, 70])

To sort names by scores:

sorted_indices = np.argsort(scores)[::-1]
print("Top performers:", names[sorted_indices])

Output:

['Bob' 'Alice' 'Charlie']


⚠️ Common Mistakes to Avoid

Mistake Fix
Using .sort() expecting return value It sorts in place, use np.sort() for copy
Forgetting to reverse for descending Use [::-1] or multiply array by -1
Confusing indices with values Use argsort() to get indices, not values
Using searchsorted() on unsorted array Always sort before using it

🧾 Summary Table: Sorting and Searching

Function Purpose
np.sort() Returns a sorted copy
array.sort() Sorts array in place
np.argsort() Returns indices that would sort
np.searchsorted() Finds insert position in sorted array
np.where() Finds indices matching condition
np.nonzero() Finds indices of non-zero values

πŸ”š Wrapping Up Chapter 9

Congratulations! πŸŽ‰
You now know how to:

  • Sort arrays (even by another array’s order)

  • Extract top and bottom performers

  • Find or insert elements in a sorted context

Sorting and searching are critical in:

  • Data analytics

  • Ranking systems

  • Indexing databases

  • Signal processing

  • Machine learning pre-processing


πŸ”œ Next in Chapter 10: Random Numbers and Simulations

We’ll explore:

  • np.random module

  • Generating random numbers

  • Simulating dice rolls, experiments, and more

Leave a Reply

Your email address will not be published. Required fields are marked *