Python - 查找应插入元素的索引以维持 Pandas 索引中的顺序
要查找应插入元素的索引以维持 Pandas 索引中的顺序,请使用index.searchsorted() 方法。
首先,导入必需的库 −
import pandas as pd
创建 Pandas 索引 −
index = pd.Index([10, 20, 30, 40, 50])
显示 Pandas 索引 −
print("Pandas Index...\n",index)Searchsorted:设置要插入的值并获取应放置的确切索引位置 −
print("\nThe exact positions where the element should be placed?...\n",index.searchsorted(45))示例
以下为该代码 −
import pandas as pd
# Creating Pandas index
index = pd.Index([10, 20, 30, 40, 50])
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# searchsorted
# set the value to insert and get the exact index position where it should be placed
print("\nThe exact positions where the element should be placed?...\n",index.searchsorted(45))输出
将生成以下输出 −
Pandas Index... Int64Index([10, 20, 30, 40, 50], dtype='int64') Number of elements in the index... 5 The exact positions where the element should be placed?... 4
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP