Python Pandas - 如何對多重索引進行排序


要建立多索引,可以使用 from_arrays() 方法。但是,要對多索引進行排序,請在 Pandas 中使用 multiIndex.sortlevel() 方法。

首先,匯入必需的庫 −

import pandas as pd

多索引是 panda 物件的多級或層次索引物件。建立陣列 −

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

"names" 引數設定每個索引級別的名稱。from_arrays() 用於建立 MultiInde −

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

對多索引排序。預設情況下,在級別 0 進行排序 −

print("\nSort MultiIndex...\n",multiIndex.sortlevel())

示例

以下是程式碼 −

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[2, 4, 3, 1], ['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)

# Sort MultiIndex
# The default sorts at level 0
print("\nSort MultiIndex...\n",multiIndex.sortlevel())

輸出

這將生成以下輸出 −

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

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

Sort MultiIndex...
(MultiIndex([(1, 'Chris'),
             (2,  'John'),
             (3, 'Jacob'),
             (4,   'Tim')],
names=['ranks', 'student']), array([3, 0, 2, 1], dtype=int64))

更新於: 19-Oct-2021

819 瀏覽

開啟你的 事業

完成課程以獲得認證

開始
廣告