在Pandas中,Series除了简单的整数索引和标签索引外,还支持复合索引(MultiIndex)。复合索引允许Series拥有多级的行和列标签。本文介绍几种将Pandas Series的复合索引提取为单独列的方法。
.reset_index()方法
.reset_index()方法可以将Series的索引重置为整数索引,原来的复合索引会被提取为列:
python
s = pd.Series(np.random.randn(6),
index=[['a', 'a', 'b', 'b', 'c', 'c'],
[1, 2, 1, 2, 1, 2]])
s.reset_index()
# 输出:
a b c 0
0 1 1 1 -0.204708
1 2 2 2 -0.519439
2 1 1 1 -0.555730
3 2 2 2 1.965781
4 1 1 1 1.393406
5 2 2 2 0.092908
unstack()方法
.unstack()方法可以将Series的复合索引展开为DataFrame。原来的索引级别会成为DataFrame的列:
python
s.unstack()
# 输出:
1 2
a -0.204708 -0.519439
b -0.555730 1.965781
c 1.393406 0.092908
修改`.index`方法
也可以直接修改Series的`.index`属性,将其设置为单一索引,原来的复合索引的值会被提取为列:
python
s.index = s.index.droplevel(0)
# 输出:
a b c
1 -0.204708 1.393406
2 -0.519439 0.092908
1 -0.555730
2 1.965781
所以Pandas提供了多种方便的方法,可以非常灵活地将Series的复合索引提取为单独的列。