Python Pandas - 計算索引和掩碼以獲取新的索引,即使對於非唯一值物件也是如此


要針對新的索引計算索引器和掩碼,即使是非唯一值物件,請使用 index.get_indexer_non_unique() 方法。Python Pandas - 計算新的索引的索引器和掩碼,即使對於非唯一值物件也是如此

首先匯入必需的庫 −

import pandas as pd

使用一些非唯一值建立 Pandas 索引 −

index = pd.Index([10, 20, 30, 40, 40, 50, 60, 60, 60, 70])

顯示 Pandas 索引 −

print("Pandas Index...\n",index)

計算索引器和掩碼。用 -1 標記,因為它不在索引中。這也計算非唯一索引物件值 −

print("\nGet the indexes...\n",index.get_indexer_non_unique([30, 40, 90, 100, 50, 60]))

示例

以下為程式碼 −

import pandas as pd

# Creating Pandas index with some non-unique values
index = pd.Index([10, 20, 30, 40, 40, 50, 60, 60, 60, 70])

# 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)

# Compute indexer and mask
# Marked by -1, as it is not in index
# This also computes non-unique Index object values
print("\nGet the indexes...\n",index.get_indexer_non_unique([30, 40, 90, 100, 50, 60]))

輸出

這將生成以下輸出 −

Pandas Index...
Int64Index([10, 20, 30, 40, 40, 50, 60, 60, 60, 70], dtype='int64')

Number of elements in the index...
10

Get the indexes...
(array([ 2, 3, 4, -1, -1, 5, 6, 7, 8], dtype=int64), array([2, 3], dtype=int64))

更新於: 14-Oct-2021

94 次瀏覽

開啟你的 事業

完成課程獲取認證

開始吧
廣告