pandas层次化索引
1. 创建多层行索引
1) 隐式构造
最常见的方法是给DataFrame构造函数的index参数传递两个或更多的数组
- Series也可以创建多层索引
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
s = Series(data = [1,2,3,"a"], index = [["a","a","b","b"],["期中","期末","期中","期末"]])
s
a 期中 1
c 期末 2
b 期中 3
d 期末 a
dtype: object
df = DataFrame(data = [1,2,3,"a"],
index = [["a","a","b","b"],["期中","期末","期中","期末"]],columns = ["Python"])
df
Python | ||
---|---|---|
a | 期中 | 1 |
期末 | 2 | |
b | 期中 | 3 |
期末 | a |
#三层索引
df = DataFrame(data = np.random.randint(0,150,size = 8),
index = [["a","a","a","a","b","b","b","b"],
["期中","期中","期末","期末","期中","期中","期末","期末"],
["一单元","二单元","一单元","二单元","一单元","二单元","一单元","二单元"]],
columns = ["Python"])
df
Python | |||
---|---|---|---|
a | 期中 | 一单元 | 79 |
二单元 | 92 | ||
期末 | 一单元 | 84 | |
二单元 | 93 | ||
b | 期中 | 一单元 | 10 |
二单元 | 129 | ||
期末 | 一单元 | 38 | |
二单元 | 33 |
2) 显示构造pd.MultiIndex
- 使用数组
df1 = DataFrame(data = np.random.randint(0,150,size = 8),
index = pd.MultiIndex.from_arrays([["a","a","a","a","b","b","b","b"],
["期中","期中","期末","期末","期中","期中","期末","期末"],
["一单元","二单元","一单元","二单元","一单元","二单元","一单元","二单元"]]),
columns = ["Python"])
df1
Python | |||
---|---|---|---|
a | 期中 | 一单元 | 19 |
二单元 | 102 | ||
期末 | 一单元 | 56 | |
二单元 | 11 | ||
b | 期中 | 一单元 | 58 |
二单元 | 38 | ||
期末 | 一单元 | 95 | |
二单元 | 26 |
df1.index
MultiIndex(levels=[['a', 'b'], ['期中', '期末'], ['一单元', '二单元']],
labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]])
df1.columns
Index(['Python'], dtype='object')
#可以把行索引变换成列索引
df2 = DataFrame(data = np.random.randint(0,150,size = (1,8)),
columns = pd.MultiIndex.from_arrays([["a","a","a","a","b","b","b","b"],
["期中","期中","期末","期末","期中","期中","期末","期末"],
["一单元","二单元","一单元","二单元","一单元","二单元","一单元","二单元"]]),
index = ["Python"])
df2
a | b | |||||||
---|---|---|---|---|---|---|---|---|
期中 | 期末 | 期中 | 期末 | |||||
一单元 | 二单元 | 一单元 | 二单元 | 一单元 | 二单元 | 一单元 | 二单元 | |
Python | 121 | 143 | 120 | 82 | 105 | 126 | 101 | 59 |
- 使用tuple
df3 = DataFrame(np.random.randint(0,150,size = 4),
index = pd.MultiIndex.from_tuples([("a",1),('a',2),("b",1),("b",2)]),columns = ["Python"])
df3
Python | ||
---|---|---|
a | 1 | 69 |
2 | 132 | |
b | 1 | 7 |
2 | 86 |
-
使用product
最简单,推荐使用
df4 = DataFrame(np.random.randint(0,150,size = (8,2)),
index = pd.MultiIndex.from_product([list("abcd"), ["期中","期末"]]),
columns = ["Python","高数"])
df4
Python | 高数 | ||
---|---|---|---|
a | 期中 | 14 | 129 |
期末 | 40 | 74 | |
b | 期中 | 83 | 103 |
期末 | 44 | 62 | |
c | 期中 | 95 | 141 |
期末 | 55 | 103 | |
d | 期中 | 42 | 68 |
期末 | 51 | 71 |
============================================
练习8:
- 创建一个DataFrame,表示出张三李四期中期末各科成绩
============================================
df = DataFrame(data = np.random.randint(0,150,size = (4,4)),
index = [["张三","张三","李四","李四"],["期中","期末","期中","期末"]],
columns = ["Python","Html","Java","PHP"])
df
Python | Html | Java | PHP | ||
---|---|---|---|---|---|
张三 | 期中 | 6 | 96 | 146 | 23 |
期末 | 139 | 136 | 84 | 77 | |
李四 | 期中 | 145 | 94 | 24 | 110 |
期末 | 95 | 16 | 34 | 34 |
2. 多层列索引
除了行索引index,列索引columns也能用同样的方法创建多层索引
#可以把行索引变换成列索引
df2 = DataFrame(data = np.random.randint(0,150,size = (1,8)),
columns = pd.MultiIndex.from_arrays([["a","a","a","a","b","b","b","b"],
["期中","期中","期末","期末","期中","期中","期末","期末"],
["一单元","二单元","一单元","二单元","一单元","二单元","一单元","二单元"]]),
index = ["Python"])
df2
a | b | |||||||
---|---|---|---|---|---|---|---|---|
期中 | 期末 | 期中 | 期末 | |||||
一单元 | 二单元 | 一单元 | 二单元 | 一单元 | 二单元 | 一单元 | 二单元 | |
Python | 141 | 82 | 39 | 6 | 16 | 69 | 19 | 22 |
3. 多层索引对象的索引与切片操作
1)Series的操作
【重要】对于Series来说,直接中括号[]与使用.loc()完全一样,因此,推荐使用中括号索引和切片。
(1) 索引
s = Series(data = [1,2,3,"a"], index = [["a","a","b","b"],["期中","期末","期中","期末"]])
s
a 期中 1
期末 2
b 期中 3
期末 a
dtype: object
s["a"]["期末"]
2
s["a","期末"]
2
s["a","jhdsajdasjk"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-23-768e71c3a49c> in <module>()
----> 1 s["a","jhdsajdasjk"]
C:anacondalibsite-packagespandascoreseries.py in __getitem__(self, key)
662 key = check_bool_indexer(self.index, key)
663
--> 664 return self._get_with(key)
665
666 def _get_with(self, key):
C:anacondalibsite-packagespandascoreseries.py in _get_with(self, key)
675 if isinstance(key, tuple):
676 try:
--> 677 return self._get_values_tuple(key)
678 except Exception:
679 if len(key) == 1:
C:anacondalibsite-packagespandascoreseries.py in _get_values_tuple(self, key)
723
724 # If key is contained, would have returned by now
--> 725 indexer, new_index = self.index.get_loc_level(key)
726 return self._constructor(self._values[indexer],
727 index=new_index).__finalize__(self)
C:anacondalibsite-packagespandascoreindexesmulti.py in get_loc_level(self, key, level, drop_level)
2246
2247 return (self._engine.get_loc(
-> 2248 _values_from_object(key)), None)
2249
2250 else:
pandas/_libs/index.pyx in pandas._libs.index.MultiIndexObjectEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.MultiIndexObjectEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: ('a', 'jhdsajdasjk')
s[['a',"期中"]]
#写两个 的时候,只会取第一个,之后就不管了
a 期中 1
期末 2
dtype: object
(2) 切片
s["a":"b"]
a 期中 1
期末 2
b 期中 3
期末 a
dtype: object
s["期中":"期末"]
Series([], dtype: object)
#多层索引,自然数的索引从0开始的,有多少行算多少行,和总体的数据有关!!!
s.iloc[0:3]
a 期中 1
期末 2
b 期中 3
dtype: object
2)DataFrame的操作
(1) 可以直接使用列名称来进行列索引
(2) 使用行索引需要用ix(),loc()等函数
【极其重要】推荐使用loc()函数
注意在对行索引的时候,若一级行索引还有多个,对二级行索引会遇到问题!也就是说,无法直接对二级索引进行索引,必须让二级索引变成一级索引后才能对其进行索引!
df4
#想要a,期中的Python的成绩
Python | 高数 | ||
---|---|---|---|
a | 期中 | 14 | 129 |
期末 | 40 | 74 | |
b | 期中 | 83 | 103 |
期末 | 44 | 62 | |
c | 期中 | 95 | 141 |
期末 | 55 | 103 | |
d | 期中 | 42 | 68 |
期末 | 51 | 71 |
df4["Python"]["a"]["期中"]
14
df4["Python"]["a","期中"]
14
df4.loc['b', "期末"]["Python"]
44
============================================
练习9:
-
分析比较Series和DataFrame各种索引的方式,熟练掌握.loc()方法
-
假设张三再一次在期中考试的时候因为特殊原因放弃英语考试,如何实现?
============================================
4. 索引的堆(stack)
stack()
unstack()
小技巧】使用stack()的时候,level等于哪一个,哪一个就消失,出现在行里。
【小技巧】使用unstack()的时候,level等于哪一个,哪一个就消失,出现在列里。
============================================
练习10:
-
使用unstack()将ddd变为两行,分别为期中期末
-
使用unstack()将ddd变为四行,分别为四个科目
============================================
5. 聚合操作
【注意】
-
需要指定axis
-
【小技巧】和unstack()相反,聚合的时候,axis等于哪一个,哪一个就保留。
所谓的聚合操作:平均数,方差,最大值,最小值……
============================================
练习11:
-
计算各个科目期中期末平均成绩
-
计算各科目张三李四的最高分
============================================