Python Pandas - 如何使用每個索引級別的名稱來建立一個 MultiIndex


若要建立一個 MultiIndex,請使用 pandas.MultiIndex.from_arrays() 方法。若要設定每個索引級別的名稱,請使用 names 引數。

首先,匯入所需的庫 −

import pandas as pd

MultiIndex 是 pandas 物件的多層次或分層索引物件。建立陣列 −

arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

“names”引數設定每個索引級別的名稱。from_arrays() 用於建立一個 Multiindex −

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

顯示 Multiindex −

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

獲取 Multiindex 中各層次的名稱 −

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

示例

以下是程式碼 −

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)

輸出

輸出如下 −

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']

更新於: 2021 年 10 月 19 日

527 次瀏覽

開啟 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.