Python Pandas - 計算輸入標籤的分片索引器


要計算輸入標籤的分片索引器,請使用 index.slice_indexer() 方法。首先,匯入所需的庫 -

import pandas as pd

建立 Pandas 索引物件 -

index = pd.Index(list('pqrstuvwxyz'))

顯示 Pandas 索引 -

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

獲取分片索引器。“開始”是開始的標籤。“結束”是要結束的標籤 -

print("\nThe slice indexer with start and stop...\n",index.slice_indexer(start='s', end='w'))

示例

以下是程式碼 -

import pandas as pd

# create Pandas index object
index = pd.Index(list('pqrstuvwxyz'))

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

# Get the slice indexer
# The "start" is the label to begin with
# The "end" is the label to end with
print("\nThe slice indexer with start and stop...\n",index.slice_indexer(start='s', end='w'))

輸出

它將生成以下輸出 -

Pandas Index...
Index(['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], dtype='object')

Number of elements in the index...
11

The slice indexer with start and stop...
slice(3, 8, None)

更新日期:14-10-2021

167 次瀏覽

開啟你的職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.