pandas基础——变形
import numpy as np
import pandas as pd
df = pd.read_csv('data/table.csv')
df.head()
1、透视表
(1)pivot
一般状态下,数据在DataFrame会以压缩状态存放,例如Gender列中F和M一起存放,两个类别被叠在一列中,pivot函数可将某一列作为新的cols
df.pivot(index='ID',columns='Gender',values='Height').head()
(2)pivot_table
pd.pivot_table(df,index='ID',columns='Gender',values='Height').head()
#由于功能更多,运行速度比较慢
%timeit df.pivot(index='ID',columns='Gender',values='Height')
%timeit pd.pivot_table(df,index='ID',columns='Gender',values='Height')
Pandas中提供了各种选项,下面介绍常用参数:
#aggfunc:对组内进行聚合统计,可传入各类函数,默认为mean
pd.pivot_table(df,index='School',columns='Gender',values='Height',aggfunc=