pandas之stack和unstack

本文详细介绍了Pandas库中stack和unstack函数在处理多层索引DataFrame时的作用,包括数据的重塑和转换。通过实例演示,帮助读者理解如何利用这两个方法重构数据的行和列结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录

多层索引在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值