Python Pandas——設定 MultiIndex 中的級別


要在 MultiIndex 中設定級別,請在 Pandas 中使用 MultiIndex.set_levels() 方法。首先,匯入所需庫 -

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("\nSet new levels in Multi-index...\n",multiIndex.set_levels([['p', 'q', 'r', 's'], [10, 20, 30, 40]]))

示例

以下是程式碼 -

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)

# set the levels in MultiIndex
print("\nSet new levels in Multi-index...\n",multiIndex.set_levels([['p', 'q', 'r', 's'], [10, 20, 30, 40]]))

輸出

這將產生以下輸出 -

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']]

Set new levels in Multi-index...
MultiIndex([('p', 30),
            ('q', 40),
            ('r', 20),
            ('s', 10)],
            names=['ranks', 'student'])

更新於:2021 年 10 月 19 日

796 次檢視

開啟你的職業生涯

完成課程並獲得認證

開始
廣告