12.数据透视

0.背景

  • stack将数据列旋转为行,unstack将数据的行旋转为列;
  • pivot重塑的一个快捷方式。index,重塑的索引;columns,重塑的列名;values,生成新列的值;

1.stack & unstack

import numpy as np
import pandas as pd
data = pd.DataFrame(np.arange(4*5).reshape((4,5)),
                    index=pd.Index(['beijing','shanghai','guangzhou','shenzhen'],name='city'),
                    columns=pd.Index(['one','two','three','four','five'],name='number'))
print data
data
result_stack = data.stack(dropna=False)
print result_stack
result_stack.png
result_unstack = result_stack.unstack('city')
print result_unstack
result_unstack.png

2.pivot(目前在数据处理过程中,pivot不是必要的)

import numpy as np
import pandas as pd
data = pd.DataFrame(np.arange(4*5).reshape((4,5)),
                    index=pd.Index(['beijing','shanghai','guangzhou','shenzhen'],name='city'),
                    columns=pd.Index(['one','two','three','four','five'],name='number'))
result_pivot = data.pivot('one','two')
print result_pivot
result_pivot.png

你可能感兴趣的:(12.数据透视)