NumPy Searching Arrays

M.Ramya

 Searching Arrays with NumPy

You can search an array for specific values and get the indexes where matches occur.

Using where() Method

The numpy.where() method returns the indexes of elements that satisfy a condition.

Program: 

Find the indexes where the value is 4:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 4, 4])

x = np.where(arr == 4)

print(x)

Output:

(array([3, 5, 6]),)

This shows that 4 is found at indexes 3, 5, and 6.

Program:

Find Even Numbers:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

x = np.where(arr % 2 == 0)

print(x)

Output:

(array([1,3,5,7]),)

Program:

Find Odd Numbers:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

x = np.where(arr % 2 == 1)

print(x)

Output:

(array([0, 2, 4, 6]),)

 Search in Sorted Arrays with searchsorted()

The numpy.searchsorted() method performs a binary search to find the index where a value should be inserted to maintain the sort order. It is designed for sorted arrays.

Program: 

Find index to insert 7:

import numpy as np

arr = np.array([6, 7, 8, 9])

x = np.searchsorted(arr, 7)

print(x)

Output: 

1

Explanation: 

7 fits at index 1 to maintain the sorted order.

Search from the Right:

By default, searchsorted() searches from the left.

To search from the right, use side='right

Program:

import numpy as np

arr = np.array([6, 7, 8, 9])

x = np.searchsorted(arr, 7, side='right')

print(x)

Output: 

2

Explanation: 

Starting from the right, 7 fits at index 2 to maintain order.

Search for Multiple Values:

You can also search for multiple values at once

Program:

import numpy as np

arr = np.array([1, 3, 5, 7])

x = np.searchsorted(arr, [2, 4, 6])

print(x)

Output: 

[1 2 3]

Explanation:

2 fits at index 1

4 fits at index 2

6 fits at index 3


Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send