Sorting & Searching in NumPy (sort, argsort, where Explained)

πŸ“Œ 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

FunctionDescription
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.


Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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