numpy.searchsorted#
- numpy.searchsorted(a, v, side='left', sorter=None)[源码]#
查找元素应插入以保持顺序的索引。
在已排序数组 a 中查找索引,以便如果 v 中的相应元素插入到这些索引之前,a 的顺序将得以保持。
假设 a 是已排序的
side
返回的索引 i 满足
left
a[i-1] < v <= a[i]right
a[i-1] <= v < a[i]- 参数:
- a1-D 数组类
输入数组。如果 sorter 为 None,则它必须按升序排序,否则 sorter 必须是排序它的索引数组。
- v数组类
要插入 a 中的值。
- side{‘left’, ‘right’}, 可选
如果为 ‘left’,则返回找到的第一个合适位置的索引。如果为 ‘right’,则返回最后一个这样的索引。如果没有合适的索引,则返回 0 或 N(其中 N 是 a 的长度)。
- sorter1-D 数组类, 可选
可选的整数索引数组,用于将数组 a 按升序排序。它们通常是 argsort 的结果。
- 返回:
- indices整数或整数数组
具有与 v 相同形状的插入点数组,或者如果 v 是标量,则为整数。
备注
使用二分查找来找到所需的插入点。
从 NumPy 1.4.0 开始,
searchsorted可以处理包含nan值的实数/复数数组。增强的排序顺序在sort中有说明。此函数使用与内置 Python 函数
bisect.bisect_left(side='left')和bisect.bisect_right(side='right')相同的算法,并且该算法也对 v 参数进行了矢量化。示例
>>> import numpy as np >>> np.searchsorted([11,12,13,14,15], 13) 2 >>> np.searchsorted([11,12,13,14,15], 13, side='right') 3 >>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13]) array([0, 5, 1, 2])
当使用 sorter 时,返回的索引是指 a 的已排序数组,而不是 a 本身。
>>> a = np.array([40, 10, 20, 30]) >>> sorter = np.argsort(a) >>> sorter array([1, 2, 3, 0]) # Indices that would sort the array 'a' >>> result = np.searchsorted(a, 25, sorter=sorter) >>> result 2 >>> a[sorter[result]] 30 # The element at index 2 of the sorted array is 30.