在 NumPy 数组中搜索
Numpy 提供了多种方法来搜索不同种类的数值,在本文中,我们将介绍两个重要的方法。
- numpy.where()
- numpy.searchsorted()
1. numpy.where:()它返回满足给定条件的输入数组中元素的索引。
Syntax: numpy.where(condition[, x, y])
Parameters:
- condition : When True, yield x, otherwise yield y.
- x, y : Values from which to choose. x, y and condition need to be broadcastable to some shape.
Returns:
out : [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere.
If only condition is given, return the tuple condition.nonzero(), the indices where condition is True.
以下示例演示了如何使用where()进行搜索。
Python3
# importing the module
import numpy as np
# creating the array
arr = np.array([10, 32, 30, 50, 20, 82, 91, 45])
# printing arr
print("arr = {}".format(arr))
# looking for value 30 in arr and storing its index in i
i = np.where(arr == 30)
print("i = {}".format(i))
Python3
# importing the module
import numpy as np
# creating the array
arr = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]
print("arr = {}".format(arr))
# left-most 3
print("left-most index = {}".format(np.searchsorted(arr, 3, side="left")))
# right-most 3
print("right-most index = {}".format(np.searchsorted(arr, 3, side="right")))
输出:
arr = [10 32 30 50 20 82 91 45]
i = (array([2], dtype=int64),)
如您所见,变量 i 是一个可迭代对象,其搜索值的索引作为第一个元素。我们可以通过将最后一个打印语句替换为
print("i = {}".format(i[0]))
这会将最终输出更改为
arr = [10 32 30 50 20 82 91 45]
i = [2]
2. numpy.searchsorted():该函数用于在排序数组 arr 中查找索引,这样,如果在索引之前插入元素,则 arr 的顺序仍将保留。在这里,使用二分搜索来查找所需的插入索引。
Syntax : numpy.searchsorted(arr, num, side=’left’, sorter=None)
Parameters :
- arr : [array_like] Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.
- num : [array_like]The Values which we want to insert into arr.
- side : [‘left’, ‘right’], optional.If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).
- num : [array_like, Optional] array of integer indices that sort array a into ascending order. They are typically the result of argsort.
Return : [indices], Array of insertion points with the same shape as num.
以下示例解释了searchsorted()的使用。
蟒蛇3
# importing the module
import numpy as np
# creating the array
arr = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]
print("arr = {}".format(arr))
# left-most 3
print("left-most index = {}".format(np.searchsorted(arr, 3, side="left")))
# right-most 3
print("right-most index = {}".format(np.searchsorted(arr, 3, side="right")))
输出:
arr = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6]
left-most index = 3
right-most index = 6