Để nhận bộ mã có độ dài của mỗi cấp từ MultiIndex, hãy sử dụng MultiIndex.levshape tài sản ở 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. Tạo mảng -
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
Tham số "tên" đặt tên cho mỗi cấp chỉ mục. Uu from_arrays () được sử dụng để tạo Multiindex -
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) Nhận một bộ giá trị với độ dài của mỗi cấp độ -
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape) Ví dụ
Sau đây là mã -
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
# The "names" parameter sets the names for each of the index levels
# The from_arrays() uis used to create a Multiindex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# display the Multiindex
print("The Multi-index...\n",multiIndex)
# get the integer number of levels in Multiindex
print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels)
# get the levels in Multiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
# get a tuple with the length of each level
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape) Đầu ra
Điều này sẽ tạo ra kết quả sau -
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris'),
(5, 'Keiron')],
names=['ranks', 'student'])
The number of levels in Multi-index...
2
The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
The tuple with the length of each level in a Multi-index...
(5, 5)