Python Pandas - 建立一個帶有作為列的多重索引級別的資料框


若要建立一個將其多重索引級別作為列的資料框,請在 Pandas 中使用 to_frame() 方法。

首先,匯入必需的庫 −

import pandas as pd

多重索引是一個多級或層次的索引物件,適用於熊貓物件。建立陣列 −

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

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

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

使用 to_frame() 建立一個帶有其多重索引級別作為列的資料框 −

dataFrame = multiIndex.to_frame()

示例

以下是程式碼 −

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)

# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()
dataFrame = multiIndex.to_frame()

# Display the DataFrame
print("\nThe DataFrame...\n",dataFrame)

輸出

這將產生以下輸出 −

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

The DataFrame...
                ranks  student
ranks  student
1      John        1   John
2      Tim         2   Tim
3      Jacob       3   Jacob
4      Chris       4   Chris

更新於:2021-10-19

1000 多次觀看

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告