Python Pandas - 獲取 MultiIndex 中請求標籤/級別的位置和切片索引
要獲取 MultiIndex 中請求的標籤/級別的位置和切片索引,請使用 Pandas 中的 get_loc_level() 方法。
首先,匯入必需的庫:
import pandas as pd
MultiIndex 是 pandas 物件的多級或層次索引物件:
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])顯示 MultiIndex:
print("The MultiIndex...\n",multiIndex)
獲取位置和切片索引:
print("\nGet the location and sliced index...\n",multiIndex.get_loc_level('r'))示例
以下為程式碼:
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])
# display the MultiIndex
print("The MultiIndex...\n",multiIndex)
# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)
# Get the location and sliced index
print("\nGet the location and sliced index...\n",multiIndex.get_loc_level('r'))輸出
這將產生以下輸出:
The MultiIndex...
MultiIndex([('p', 's'),
('q', 't'),
('r', 'r'),
('r', 'v'),
('s', 'w'),
('s', 'x')],
names=['One', 'Two'])
The levels in MultiIndex...
[['p', 'q', 'r', 's'], ['r', 's', 't', 'v', 'w', 'x']]
Get the location and sliced index...
(slice(2, 4, None), Index(['r', 'v'], dtype='object', name='Two'))
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP