Python Pandas - 獲取多重索引中的層級名稱
要在多重索引中獲取層級名稱,在 Pandas 中使用 MultiIndex.names 屬性。首先,匯入所需庫 −
import pandas as pd
多重索引是 pandas 物件的多層級或層次結構索引物件。建立陣列 −
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
“names”引數為每個索引層設定名稱。from_arrays() 用於建立多重索引 −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))獲取多重索引中層級的名稱 −
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)
# get the levels in Multiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)輸出
這將產生以下輸出 −
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'] The levels in Multi-index... [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP