Để tìm vị trí cho chuỗi nhãn trong MultiIndex, hãy sử dụng MutiIndex.get_locs () 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('pqrrst'), list('kytssp')])
Hiển thị MultiIndex -
print("The MultiIndex...\n",multiIndex) Nhận vị trí cho một chuỗi các nhãn -
print("\nGet the locations in MultiIndex...\n",multiIndex.get_locs('s'))
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('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')) Đầu ra
Điều này sẽ tạo ra kết quả sau -
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]