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]

更新時間:14-Oct-2021

372 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.