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 多次观看

开启您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.