import pandas as pd
import numpy as np
from pandas import DataFrame
创建方式一:元组列表
m_index1=pd.Index([("A","x1"),("A","x2"),("B","y1"),("B","y2"),("B","y3")],name=["class1","class2"])
df1=DataFrame(np.random.randint(1,10,(5,3)),index=m_index1)
df1
结果如下:
创建方式二:特定结构
例如**from_arrays()
class1=["A","A","B","B"]
class2=["x1","x2","y1","y2"]
m_index2=pd.MultiIndex.from_arrays([class1,class2],names=["class1","class2"])
df2=DataFrame(np.random.randint(1,10,(4,3)),index=m_index2)
df2
结果如下:
创建方式三:笛卡尔积
from_product()从多个集合的笛卡尔积创建MultiIndex对象。
m_index3=pd.MultiIndex.from_product([["A","B"],['x1','y1']],names=["class1","class2"])
df3=DataFrame(np.random.randint(1,10,(2,4)),columns=m_index3)
df3
MultiIndex(levels=[['A', 'B'], ['x1', 'y1']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['class1', 'class2'])
结果如下:
网友评论