文章目录
多层索引在DataFrame中提供了一种一致性方式用于重排列数据。以下是两个基础操作:
- statck(堆叠):该操作会“旋转”或将列中的数据透视到行,即将原来的列转成最内层的行索引
- unstack(拆堆):该操作会将行中的数据透视到列,即将最内层的行索引变成列
官网学习地址
图解pandas的轴旋转函数:stack和unstack
比如对于下列这样一个多层索引:
data = pd.DataFrame(np.arange(6).reshape((2, 3)),
index=pd.Index(['Ohio', 'Colorado'], name='state'),
columns=pd.Index(['one', 'two', 'three'], name='number'))
data:
number one two three
state
Ohio 0 1 2
Colorado 3 4 5
1. stack
result = data.stack()
result:
state number
Ohio one 0
two 1
three 2
Colorado one 3
two 4
three 5
dtype: int32
2. unstack
result.unstack()
输出结果:
number one two three
state
Ohio 0 1 2
Colorado 3 4 5
本文详细介绍了Pandas库中stack和unstack函数在处理多层索引DataFrame时的作用,包括数据的重塑和转换。通过实例演示,帮助读者理解如何利用这两个方法重构数据的行和列结构。
3万+

被折叠的 条评论
为什么被折叠?



