Python Pandas - 使用多級索引的層級作為列建立 DataFrame,但避免設定返回 DataFrame 的索引


要建立將多級索引的層級作為列的 DataFrame,請使用 **multiIndex.to_frame()**。**index** 引數設定為 **False** 以避免設定返回 DataFrame 的索引。

首先,匯入所需的庫:

import pandas as pd

多級索引是 pandas 物件的多級或分層索引物件。建立陣列:

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

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

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

使用 to_frame() 建立一個將多級索引的層級作為列的 DataFrame。使用 "index" 引數並將其設定為 "False" 以避免設定返回 DataFrame 的索引:

dataFrame = multiIndex.to_frame(index=False)

示例

以下是程式碼:

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()
# Use the "index" parameter and set it to "False" to avoid setting the index of the returned #DataFrame
dataFrame = multiIndex.to_frame(index=False)

# Return 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
0      1      John
1      2       Tim
2      3     Jacob
3      4     Chris

更新於: 2021年10月19日

125 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.