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
廣告