当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python numpy.searchsorted()用法及代码示例


numpy.searchsorted()函数用于在排序的数组arr中查找索引,这样,如果在索引之前插入元素,arr的顺序仍将保留。在这里,二进制搜索用于查找所需的插入索引。

用法: numpy.searchsorted(arr, num, side=’left’, sorter=None)

参数:
arr :[数组]输入数组。如果sorter为None,则必须按升序对其进行排序,否则sorter必须是对其进行排序的索引数组。
num :[数组]我们要插入到arr中的值。
side :['left','right'],可选。如果为“ left”,则给出找到的第一个合适位置的索引。如果为“正确”,则返回上一个这样的索引。如果没有合适的索引,则返回0或N(其中N是a的长度)。
num :[数组,可选]整数索引数组,将数组a升序排列。它们通常是argsort的结果。


Return :[索引],与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]


相关用法


注:本文由纯净天空筛选整理自jana_sayantan大神的英文原创作品 numpy.searchsorted() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。