Python Pandas - 獲取 MultiIndex 中的程式碼(每個標籤的位置)
要獲取 MultiIndex 中的程式碼(每個標籤的位置),請使用 Pandas 中的 MultiIndex.codes 屬性。首先,匯入必需的庫 −
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("\nThe location of each label in Multi-index...\n",multiIndex.codes)
示例
以下是程式碼 −
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 levels in Multiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
# get the location of each label in Multiindex
print("\nThe location of each label in Multi-index...\n",multiIndex.codes)輸出
這將生成以下輸出 −
The Multi-index... MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris'), (5, 'Keiron')], names=['ranks', 'student']) The levels in Multi-index... [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']] The location of each label in Multi-index... [[0, 1, 2, 3, 4], [2, 4, 1, 0, 3]]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP