Python Pandas - 計算輸入標籤的切片位置


若要計算輸入標籤的切片位置,請使用 index.slice_locs() 方法。首先,匯入必需的庫 -

import pandas as pd

建立 Pandas 索引物件 -

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

顯示 Pandas 索引 -

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

獲取切片位置。“start”是開始的標籤。“end”是結束的標籤

print("\nThe slice locations with start and stop...\n",index.slice_locs(start='q', end='v'))

示例

以下是程式碼 -

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 locations
# The "start" is the label to begin with
# The "end" is the label to end with
print("\nThe slice locations with start and stop...\n",index.slice_locs(start='q', end='v'))

輸出

這將產生以下輸出 -

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 locations with start and stop...
(1, 7)

更新於: 14-Oct-2021

82 次瀏覽

啟動你的職業生涯

完成課程認證

立即開始
廣告
© . All rights reserved.