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 *