๐ Introduction
When working with data, you often need to sort values or find specific elements.
With NumPy, this becomes fast and efficient using built-in functions.
๐ Why Sorting & Searching Matter?
They help you:
- Organize data
- Find values quickly
- Prepare datasets for analysis
๐งช Example Dataset
import numpy as nparr = np.array([40, 10, 30, 20])
๐ข 1. Sorting Arrays (sort())
print(np.sort(arr))
๐ Output:
[10 20 30 40]
โ Returns a sorted copy (original unchanged)
๐ Sort Original Array
arr.sort()
print(arr)
โ Modifies original array
๐ 2. argsort() (Get Indices)
arr = np.array([40, 10, 30, 20])print(np.argsort(arr))
๐ Output:
[1 3 2 0]
โ Returns index positions of sorted elements
๐ 3. where() (Find Elements)
arr = np.array([10, 20, 30, 40])print(np.where(arr > 25))
๐ Output:
(array([2, 3]),)
โ Returns indices where condition is true
๐ 4. Searching in 2D Arrays
arr = np.array([[1,2],[3,4]])print(np.where(arr > 2))
โก Why Use NumPy for Sorting?
Using NumPy:
- Faster than Python lists
- Handles large datasets
- Provides advanced functions
๐ฆ Real-World Example
marks = np.array([85, 60, 90, 70])sorted_marks = np.sort(marks)
print(sorted_marks)
โ Useful in:
- Ranking systems
- Data analysis
- Machine learning
๐ Used with Other Libraries
Sorting & searching are widely used in:
- Pandas
- Scikit-learn
- TensorFlow
๐ Summary Table
| Function | Description |
|---|---|
| sort() | Sort array |
| argsort() | Get sorted indices |
| where() | Find elements |
๐ง Pro Tips
- Use
argsort()for ranking data - Use
where()for filtering conditions - Use
sort()carefully (copy vs original)
๐ Conclusion
Sorting and searching in NumPy help you organize and analyze data efficiently.