官方文档:https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html
官方给出的说明是:
即:查询给定数据在原始数组中的插入位置,而不改变原始数组的排列顺序。
代码测试:
print(np.searchsorted([1,2,3,4,5], 3))
print(np.searchsorted([1,2,3,4,5], 3, side='right'))
print(np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3]))
"""
输出:
2
3
[0 5 1 2]
"""
给定已经排序完成的数组,在数组中插入'3'和新数组'[-10, 10, 2, 3]',而不改变原始数组的排列顺序。返回插入数值的下标。
当给定的数组乱序排列时,可借助参数'sorter'完成对给定数组的排列之后,再寻找插入给定数值的下标位置,如下:
print(np.searchsorted([1,2,6,3,4,5], 4)) # 不调用sorter参数
print(np.searchsorted([1,2,6,3,4,5], 4, sorter=np.argsort([1,2,6,3,4,5]))) # 调用sorter参数
"""
输出:
4
3
"""
参考:
https://blog.csdn.net/qq_33757398/article/details/89876088