Python中的numpy.searchsorted()
numpy.searchsorted()函数用于寻找排序后的数组arr的索引,这样,如果在索引之前插入元素,Arr的顺序仍然会被保留下来。这里,二进制搜索被用来寻找所需的插入索引。
语法: numpy.searchsorted(arr, num, side=’left’, sorter=None)
参数 :
arr : [array_like] 输入数组。如果sorter是None,那么它必须以升序排序,否则sorter必须是一个能排序的索引数组。
num : [array_like]我们想插入arr的值。
side : [‘left’, ‘right’], optional.如果是’left’,则给出找到的第一个合适位置的索引。如果是’右’,则返回最后一个这样的索引。如果没有合适的索引,返回0或N(其中N是a的长度)。
num : [array_like, Optional] 将数组a排序为升序的整数索引数组。它们通常是argsort的结果。
返回 : [indices], 与num形状相同的插入点阵列。
代码#1:
# Python program explaining
# searchsorted() function
import numpy as geek
# input array
in_arr = [2, 3, 4, 5, 6]
print ("Input array : ", in_arr)
# the number which we want to insert
num = 4
print("The number which we want to insert : ", num)
out_ind = geek.searchsorted(in_arr, num)
print ("Output indices to maintain sorted array : ", out_ind)
输出 :
Input array : [2, 3, 4, 5, 6]
The number which we want to insert : 4
Output indices to maintain sorted array : 2
代码#2:
# Python program explaining
# searchsorted() function
import numpy as geek
# input array
in_arr = [2, 3, 4, 5, 6]
print ("Input array : ", in_arr)
# the number which we want to insert
num = 4
print("The number which we want to insert : ", num)
out_ind = geek.searchsorted(in_arr, num, side ='right')
print ("Output indices to maintain sorted array : ", out_ind)
输出 :
Input array : [2, 3, 4, 5, 6]
The number which we want to insert : 4
Output indices to maintain sorted array : 3
代码#3:
# Python program explaining
# searchsorted() function
import numpy as geek
# input array
in_arr = [2, 3, 4, 5, 6]
print ("Input array : ", in_arr)
# the numbers which we want to insert
num = [4, 8, 0]
print("The number which we want to insert : ", num)
out_ind = geek.searchsorted(in_arr, num)
print ("Output indices to maintain sorted array : ", out_ind)
输出 :
Input array : [2, 3, 4, 5, 6]
The number which we want to insert : [4, 8, 0]
Output indices to maintain sorted array : [2 5 0]