Python Pandas - 從 MultiIndex 獲取一個包含每個級別長度的元組
要從 MultiIndex 獲取包含每個級別長度的元組,請在 Pandas 中使用 MultiIndex.levshape 屬性。
首先,匯入所需的庫 −
import pandas as pd
MultiIndex 是 Pandas 物件的多級或層次化索引物件。建立陣列 −
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
"names" 引數為每個索引級別設定名稱。from_arrays() uis 用於建立 Multiindex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))獲取一個包含每個級別長度的元組 −
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape)示例
以下是程式碼 −
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)輸出
這將產生以下輸出 −
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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP