Để nhận vị trí và chỉ mục cắt cho nhãn / cấp được yêu cầu trong MultiIndex, hãy sử dụng get_loc_level () trong Pandas.
Đầu tiên, hãy nhập các thư viện được yêu cầu -
import pandas as pd
MultiIndex là một đối tượng chỉ mục đa cấp hoặc phân cấp cho các đối tượng gấu trúc -
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two']) Hiển thị MultiIndex -
print("The MultiIndex...\n",multiIndex)
Nhận vị trí và chỉ mục cắt -
print("\nGet the location and sliced index...\n",multiIndex.get_loc_level('r')) Ví dụ
Sau đây là mã -
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')) Đầu ra
Điều này sẽ tạo ra kết quả sau -
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'))