多重索引被定义为非常重要的索引,因为它涉及到数据分析和操作,特别是在处理高维数据时。它还能够在较低维度的数据结构(如 Series 和 DataFrame)中存储和操作具有任意数量维度的数据。

它是标准索引对象的分层类比,用于存储 pandas 对象中的轴标签。它还可以被定义为元组数组,其中每个元组是唯一的。它可以从数组列表、元组数组和交叉可迭代对象的集合中创建。

示例:

arrays = [['it', 'it', 'of', 'of', 'for', 'for', 'then', 'then'],  
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]  
tuples = list(zip(*arrays))  
tuples  

输出:

 [('it', 'one'),
 ('it', 'two'),
 ('of', 'one'),
 ('of', 'two'),
 ('for', 'one'),
 ('for', 'two'),
 ('then', 'one'),
 ('then', 'two')]

示例2:

arrays = [['it', 'it', 'of', 'of', 'for', 'for', 'then', 'then'],  
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]  
tuples = list(zip(*arrays))  
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])  

输出:

MultiIndex([('bar', 'one'),
 [('it', 'one'),
 ('it', 'two'),
 ('of', 'one'),
 ('of', 'two'),
 ('for', 'one'),
 ('for', 'two'),
 ('then', 'one'),
 ('then', 'two')]
 names=['first', 'second'])

示例3:

import pandas as pd  
import numpy as np  
pd.MultiIndex(levels=[[np.nan, None, pd.NaT, 128, 2]],   
codes=[[0, -1, 1, 2, 3, 4]])  

输出:

MultiIndex(levels=[[nan, None, NaT, 128, 2]],
           codes=[[0, -1, 1, 2, 3, 4]])

标签: Pandas, Pandas教程, Pandas库, Pandas基础, Pandas学习, Pandas使用, Pandas指南, Pandas入门教程, Pandas模块, Pandas数据库, Pandas实战教程, Pandas用法总结, Pandas文档