Python Pandas - 将 MultiIndex 转换为包含级别值的元组索引

pythonserver side programmingprogramming更新于 2026/1/20 13:32:17

要将 MultiIndex 转换为包含级别值的元组索引,请使用 MultiIndex.to_flat_index() 方法。

首先,导入所需的库 −

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("\nConverting a MultiIndex to an Index of Tuples including the level values...\n",multiIndex.to_flat_index())

示例

以下是代码 −

import pandas as pd

# MultiIndex 是一个熊猫对象的多级或分层索引对象
# 创建数组
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

# "names"参数设置每个索引级别的名称
# from_arrays() 用于创建 MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

# 显示 MultiIndex
print("The Multi-index...\n",multiIndex)

# 获取 MultiIndex 中的级别
print("\nThe levels in Multi-index...\n",multiIndex.levels)

# 转换 MultiIndex
print("\nConverting a MultiIndex to an Index of Tuples including the level values...\n",multiIndex.to_flat_index())

输出

这将产生以下输出 −

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

Converting a MultiIndex to an Index of Tuples containing the level values...
   Index([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], dtype='object')

相关文章


有用资源