Python Pandas - 將多索引轉換為包含級別值的元組的索引


要將多索引轉換為包含級別值的元組的索引,請使用 MultiIndex.to_flat_index() 方法。

首先,匯入所需的庫 −

import pandas as pd

MultiIndex 是一個多層級或分層級 pandas 物件索引物件。建立陣列 −

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

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

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

轉換 MultiIndex −

print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",multiIndex.to_flat_index())

示例

以下是程式碼 −

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

# 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)

# Convert the MultiIndex
print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",multiIndex.to_flat_index())

輸出

這會產生以下輸出 −

The Multi-index...
MultiIndex([(1,  'John'),
            (2,   'Tim'),
            (3, 'Jacob'),
            (4, 'Chris')],
            names=['ranks', 'student'])

The levels in Multi-index...
   [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]

Converting a MultiIndex to an Index of Tuples containing the level values...
   Index([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], dtype='object')

更新於: 19-Oct-2021

1K+ 瀏覽量

Kickstart Your Career

透過完成課程獲得認證

開始
廣告
© . All rights reserved.