约定第一行代码
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
MultiIndex
MultiIndex表示多级索引,它是从Index继承过来的,其中多级标签用元组对象来表示
一、创建MultiIndex对象
创建方式一:元组列表
m_index1=pd.Index([("A","x1"),("A","x2"),("B","y1"),("B","y2"),("B","y3")],name=["class1","class2"])
m_index1
#代码结果
MultiIndex(levels=[['A', 'B'], ['x1', 'x2', 'y1', 'y2', 'y3']],
labels=[[0, 0, 1, 1, 1], [0, 1, 2, 3, 4]],
names=['class1', 'class2'])
df1 = Dataframe(np.random.randint(1,10,(5,3)),index = m_inex1)
df1
代码结果
0 | 1 | 2 | ||
---|---|---|---|---|
class1 | class2 | |||
A | x1 | 4 | 1 | 2 |
x2 | 1 | 2 | 6 | |
B | y1 | 6 | 1 | 8 |
y2 | 8 | 8 | 6 | |
y3 | 6 | 9 | 3 |
创建方式二:特定结构
class1=["A","A","B","B"]
class2=["x1","x2","y1","y2"]
m_index2=pd.MultiIndex.from_arrays([class1,class2],names=["class1","class2"])
m_index2
#代码结果
MultiIndex(levels=[['A', 'B'], ['x1', 'x2', 'y1', 'y2']],
labels=[[0, 0, 1, 1], [0, 1, 2, 3]],
names=['class1', 'class2'])
df2=DataFrame(np.random.randint(1,10,(4,3)),index=m_index2)
df2
代码结果
0 | 1 | 2 | ||
---|---|---|---|---|
class1 | class2 | |||
A | x1 | 4 | 1 | 2 |
x2 | 1 | 2 | 6 | |
B | y1 | 6 | 1 | 8 |
y2 | 8 | 8 | 6 |
创建方式三:笛卡尔积
.from_product()从多个集合的笛卡尔积创建MultiIndex对象
m_index3=pd.MultiIndex.from_product([["A","B"],['x1','y1']],names=["class1","class2"])
m_index3
#代码结果
MultiIndex(levels=[['A', 'B'], ['x1', 'y1']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['class1', 'class2'])
df3 = pd.DataFrame(np.random.randint(1,10,(2,4)),columns = m_index3)
class1 | A | B | ||
---|---|---|---|---|
class2 | x1 | x2 | x1 | x2 |
0 | 1 | 4 | 1 | 2 |
1 | 1 | 2 | 1 | 4 |
MultiIndex对象属性
我们再来看一下df1的结构
0 | 1 | 2 | ||
---|---|---|---|---|
class1 | class2 | |||
A | x1 | 4 | 1 | 2 |
x2 | 1 | 2 | 6 | |
B | y1 | 6 | 1 | 8 |
y2 | 8 | 8 | 6 | |
y3 | 6 | 9 | 3 |
- 如何获取到单个元素
df1.loc[('A','x1'),2]
#代码结果
2
- 通过索引下标取索引值
m_index4=df1.index
print(m_index4[0])
#代码结果
('A', 'x1')
- 调用.get_loc()和.get_indexer()获取标签的下标
print(m_index4.get_loc(("A","x2")))
print(m_index4.get_indexer([("A","x2"),("B","y1"),"nothing"]))
#代码结果
1
[ 1 2 -1]
- MultiIndex对象使用多个Index对象保存索引中每一级的标签
print(m_index4.levels[0])
print(m_index4.levels[1])
#代码结果
Index(['A', 'B'], dtype='object', name='class1')
Index(['x1', 'x2', 'y1', 'y2', 'y3'], dtype='object', name='class2')
- MultiIndex对象还有属性labels保存标签的下标
print(m_index4.labels[0])
print(m_index4.labels[1])
#代码结果
FrozenNDArray([0, 0, 1, 1, 1], dtype='int8')
FrozenNDArray([0, 1, 2, 3, 4], dtype='int8')