Python Pandas - 在 MultiIndex 中獲取標籤序列的位置
要獲取 MultiIndex 中標籤序列的位置,請在 Pandas 中使用 MutiIndex.get_locs() 方法。
首先,匯入所需的庫 −
import pandas as pd
MultiIndex 是 pandas 物件的多級或層次化的索引物件 −
multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')])
顯示 MultiIndex −
print("The MultiIndex...\n",multiIndex)獲取標籤序列的位置 −
print("\nGet the locations in MultiIndex...\n",multiIndex.get_locs('s'))
示例
以下為程式碼 −
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')])
# display the MultiIndex
print("The MultiIndex...\n",multiIndex)
# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)
# Get the location for a sequence of labels
print("\nGet the locations in MultiIndex...\n",multiIndex.get_locs('s'))輸出
這將產生以下輸出 −
The MultiIndex...
MultiIndex([('p', 'k'),
('q', 'y'),
('r', 't'),
('r', 's'),
('s', 's'),
('t', 'p')],
)
The levels in MultiIndex...
[['p', 'q', 'r', 's', 't'], ['k', 'p', 's', 't', 'y']]
Get the locations in MultiIndex...
[4]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP