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']
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP