Python - 使用 Python 在 Pandas index 中查找应插入的值(作为数组传递)以维护顺序的索引
要查找应插入的值(作为数组传递)的索引以维护 Pandas index 中的顺序,请使用 index.searchsorted() 方法。
首先,导入所需库 −
import pandas as pd
创建 Pandas index −
index = pd.Index([10, 20, 30, 40, 50])
显示 Pandas index −
print("Pandas Index...\n",index)
Searchsorted − 将要插入的值设为数组并获取应放置这些值的准确索引位置 −
print("\nThe exact positions where the values should be placed?...\n",index.searchsorted([35, 60]))
示例
以下是代码 −
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 values to insert like an array and get the exact index positions # where these values should be placed print("\nThe exact positions where the values should be placed?...\n",index.searchsorted([35, 60]))
输出
这将生成以下输出:
Pandas Index... Int64Index([10, 20, 30, 40, 50], dtype='int64') Number of elements in the index... 5 The exact positions where the values should be placed?... [3 5]
广告