NumPy Array Search

doorzoek een array

U kunt een waarde in een array zoeken (opzoeken) en vervolgens de verkregen indexen retourneren.

Om een array te doorzoeken, gebruik dan where() methode.

Example

zoek de indexen van de waarde 4:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)

Run Instance

bijvoorbeeld, het zou een tuple retourneren:(array([3, 5, 6],)

wat betekent dat de waarde 4 voorkomt op indexen 3, 5 en 6.

Example

zoek de indexen van eveneens waarden:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 0)
print(x)

Run Instance

Example

zoek de indexen van waarden die oneven zijn:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 1)
print(x)

Run Instance

zoeksorteren

er is een genaamd searchsorted() methode, die in een array een binair zoeken uitvoert en de index retourneert waarin de opgegeven waarde moet worden ingevoegd om de zoekvolgorde te behouden.

aannemen searchsorted() The method is used for sorting arrays.

Example

Find the index where the value 7 should be inserted:

import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7)
print(x)

Run Instance

Example Explanation:The number 7 should be inserted at index 1 to maintain the sorted order.

This method searches from the left and returns the first index where the number 7 is no longer greater than the next value.

Search from the Right

By default, the leftmost index is returned, but we can specify side='right'to return the rightmost index.

Example

Search from the right to find the index where the value 7 should be inserted:

import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7, side='right')
print(x)

Run Instance

Example Explanation:The number 7 should be inserted at index 2 to maintain the sorted order.

This method searches from the right and returns the first index where the number 7 is no longer less than the next value.

Multiple Values

To search for multiple values, use an array with specified values.

Example

Find the index where the values 2, 4, and 6 should be inserted:

import numpy as np
arr = np.array([1, 3, 5, 7])
x = np.searchsorted(arr, [2, 4, 6])
print(x)

Run Instance

The return value is an array:[1 2 3] Contains three indexes, where 2, 4, and 6 will be inserted into the original array to maintain order.