Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas - Cách tạo MultiIndex với tên của từng cấp chỉ mục

Để tạo MultiIndex, hãy sử dụng pandas.MultiIndex.from_arrays () phương pháp. Để đặt tên của từng cấp chỉ mục, hãy sử dụng tên tham số.

Đầ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. From_arrays () được sử dụng để tạo Multiindex -

multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

Hiển thị Multiindex -

print("The Multi-index...\n",multiIndex)

Lấy tên của các cấp trong Multiindex -

print("\nThe names of levels in Multi-index...\n",multiIndex.names)

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() is 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 names of levels in Multiindex
print("\nThe names of levels in Multi-index...\n",multiIndex.names)

Đầ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 names of levels in Multi-index...
['ranks', 'student']