Python Pandas - 獲取請求標籤/級別的位置和切片索引,但不刪除級別
為了在多級索引中獲取請求標籤/級別的位置和切片索引,請在 Pandas 中使用 **get_loc_level()** 方法。使用 **drop_level** 引數並將其設定為 **False** 以避免刪除級別。
首先,匯入所需的庫 -
import pandas as pd
多級索引是 Pandas 物件的多級或分層索引物件 -
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])顯示多級索引 -
print("The MultiIndex...\n",multiIndex)
獲取位置和切片索引。為了避免刪除級別,我們使用了值為“False”的“drop_level”引數 -
print("\nGet the location and sliced index (avoid dropping the level)...\n",multiIndex.get_loc_level('r', drop_level=False))示例
以下是程式碼 -
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
# To avoid dropping a level, we have used the "drop_level" parameter with value "False"
print("\nGet the location and sliced index (avoid dropping the level)...\n",multiIndex.get_loc_level('r', drop_level=False))輸出
這將產生以下輸出 -
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 (avoid dropping the level)...
(slice(2, 4, None), MultiIndex([('r', 'r'),('r', 'v')],names=['One', 'Two']))
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP