import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(6).reshape(2,3),index=("AA","BB"),columns=["three","two","one"])
print(df)
three two one
AA 0 1 2
BB 3 4 5
表格在行列方向上均有索引(类似于DataFrame),花括号结构只有“列方向”上的索引(类似于层次化的Series),结构更加偏向于堆叠(Series-stack,方便记忆)。stack函数会将数据从”表格结构“变成”花括号结构“,即将其行索引变成列索引,反之,unstack函数将数据从”花括号结构“变成”表格结构“,即要将其中一层的列索引变成行索引
#直接列索引转换到最内层行索引,生一个Series对象
df2 = df.stack()
print(df2)
AA three 0
two 1
one 2
BB three 3
two 4
one 5
dtype: int64
df.stack()将df格式从表格形式转化成了花括号结构
# 将第二行的列索引转化成行索引
df3 = df2.unstack(0)
print(df3)
AA BB
three 0 3
two 1 4
one 2 5
# unstack()或者unstack(1)将第二行的列索引转化成行索引
df3 = df2.unstack()
print(df3)
three two one
AA 0 1 2
BB 3 4 5