本篇博客分享python中stack()与unstack()函数用法
一维表和二维表
我们最常用的源数据就是一维表,每个index都在行上。
例如下图
经过了pivot之后的表为二维表,如下图
stack()
stack()就是把二维表转化成一维表(stack为堆叠的意思,就是把所有的index都堆在行上)
unstack()
unstack() 则为stack的逆函数,即把一维表转化成二维表的过程
实例说明
import pandas as pd
import numpy as np
data=pd.DataFrame(np.arange(6).reshape((2,3)),index=pd.Index(['A','B']),columns=pd.Index(['one','two','three']))
'''
one two three
A 0 1 2
B 3 4 5
'''
df1 = data.stack()
df1
'''
A one 0
two 1
three 2
B one 3
two 4
three 5
'''
df2 = df1.unstack()
df2
'''
one two three
A 0 1 2
B 3 4 5
'''