pandas层次化索引
多级索引包括: 多级行索引 和 多级列索引
1. 创建多层行索引
1) 隐式构造
最常见的方法是给DataFrame构造函数的index参数传递两个或更多的数组
- Series也可以创建多层索引
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
index = [np.array(["期中","期中","期末","期末"]),np.array(["语文","英语","语文","英语"])]
Series(np.random.randn(4),index=index)
结果为:
期中 语文 1.040276
英语 0.456647
期末 语文 0.583853
英语 0.348378
dtype: float64
2) 显示构造pd.MultiIndex
- 使用数组
index = pd.MultiIndex.from_arrays([["期中","期中","期中","期末","期末","期末"],["语文","英语","数学","语文","英语","数学"]])
columns = ["张三","李四","王五","赵柳"]
data = np.random.randint(0,150,size=(6,4))
DataFrame(data,index,columns)
张三 | 李四 | 王五 | 赵柳 | ||
---|---|---|---|---|---|
期中 | 语文 | 12 | 146 | 61 | 121 |
英语 | 120 | 119 | 100 | 68 | |
数学 | 73 | 80 | 40 | 102 | |
期末 | 语文 | 90 | 143 | 51 | 85 |
英语 | 6 | 35 | 62 | 90 | |
数学 | 32 | 60 | 114 | 149 |
- 使用tuple
index = pd.MultiIndex.from_tuples([("期中","语文"),("期中","数学"),("期中","英语"),("期末","语文"),("期末","数学"),("期末","英语")])
columns = ["张三","李四","王五","赵柳"]
data = np.random.randint(0,150,size=(6,4))
DataFrame(data,index,columns)
张三 | 李四 | 王五 | 赵柳 | ||
---|---|---|---|---|---|
期中 | 语文 | 0 | 40 | 95 | 1 |
数学 | 112 | 137< |