Python Pandas Index.searchsorted()

Python Pandas Index.searchsorted()

Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python软件包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据更加容易。
Pandas Index.searchsorted()函数找到应该插入元素的索引,以保持顺序。该函数在一个排序的IndexOpsMixin self中找到索引,这样,如果在索引之前插入value中的相应元素,那么self的顺序将被保留下来。

语法: Index.searchsorted(value, side=’left’, sorter=None)
参数 :
value :要插入到自己的数值。
side : 如果是’left’,给出找到的第一个合适位置的索引。如果是’右’,则返回最后一个这样的索引。如果没有合适的索引,则返回0或N(其中N是self的长度)。
sorter : 可选的整数索引数组,将自己排序为升序。它们通常是np.argsort的结果。
返回: [indices : array of ints] 形状与值相同的插入点阵列。

例子#1:使用Index.searchsorted()函数找到正确的位置来插入一个元素,使索引保持排序。

# importing pandas as pd
import pandas as pd
 
# Creating the index
idx = pd.Index([1, 5, 8, 9, 11, 24, 56, 81])
 
# Print the Index
idx

输出 :

Python Pandas Index.searchsorted()

如果要插入的元素是10,让我们找到插入的位置

# to find the position of insertion
idx.searchsorted(10)

输出 :

Python Pandas Index.searchsorted()

正如我们在输出中看到的,该函数返回4,表明如果要保持顺序,在索引中插入10的正确位置是4。

例子#2:使用Index.searchsorted()函数为索引中的多个元素找到正确的插入位置。插入的时候应该保持顺序。

# importing pandas as pd
import pandas as pd
 
# Creating the index
idx = pd.Index([1, 5, 8, 9, 11, 24, 56, 81])
 
# Print the Index
idx

输出 :

Python Pandas Index.searchsorted()

如果要插入的元素是7和29,让我们找到插入的位置

# to find the position of insertion
idx.searchsorted([7, 29])

输出 :

Python Pandas Index.searchsorted()

正如我们在输出中看到的,该函数返回了2和6,表明如果要保持顺序,在索引中插入7和29的正确位置是第2和第6位。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程