《利用Python进行数据分析》 10.4 数据透视表与交叉表

10.4.1 数据透视表


1.数据透视表简介

        数据透视表是电子表格程序和其他数据分析软件中常见的数据汇总工具。它根据一个或多个键聚合一张表的数据,将数据在矩形格式中排列,其中一些分组键是沿着行的,另一些是沿着列的。

        Python中的pandas透视表是通过groupby工具以及使用分层索引的重塑操作实现的

        DataFrame拥有一个pivot_table方法,并且还有一个顶层的pandas.pivot_table函数。除了为groupby提供一个方便接口,pivot_table还可以添加部分总计,也称作边距。

示例:小费数据集操作

操作1:做计算一张在行方向上按day和smoker排列的分组平均值(默认的pivot_table聚合类型)的表(见图10-1)

源文件请查看链接:小费源文件

15259227-a9558777013641dc.png
图10-1:操作一

操作2:在tip_pct和size上进行聚合,并根据time分组。将把smoker放入表的列,而将day放入表的行(见图10-2)

15259227-5c8bf6798e1d1dc3.png
图10-2:操作2


操作3:传递margins=True来扩充这个表来包含部分总计(见图10-3)

15259227-0810ca74167a14c2.png
图10-3:操作3

注:自动添加All行和列标签,其中相应的值是单层中所有数据的分组统计值

All的值是均值,且该均值是不考虑吸烟者与非吸烟者(All列)或行分组中任何两级的(All行)


操作4:将函数传递给aggfunc使用不同的聚合函数,利用'count’或者len将给出一张分组大小的交叉表(计数或出现频率)(见图10-4)

15259227-38f51d58e6ad2b2c.png
图10-4:操作4


操作5:传递fill_value填充产生的空值(见图10-5)

15259227-740f2cdefdff2dc0.png
图10-5:操作5

10.1.2 数据交叉表


1.交叉表简介

交叉表(简写为crosstab)是数据透视表的一个特殊情况,计算的是分组中的频率

示例1:不同民族惯用手分析(见图10-6)

使用pivot_table或pandas.crosstable函数来按照国籍和惯用型来总结数据

15259227-93b74b069d893568.png
图10-6:示例1

注:(1)pandas.read_table(filepath_or_buffer,sep='\t',delimiter=None,header='infer',names=None, index_col=None,usecols=None,squeeze=False,prefix=None,mangle_dupe_cols=True, dtype=None,engine=None,converters=None,true_values=None,false_values=None, skipinitialspace=False,skiprows=None,nrows=None,na_values=None,keep_default_na=True, na_filter=True,verbose=False,skip_blank_lines=True,parse_dates=False, infer_datetime_format=False,keep_date_col=False,date_parser=None,dayfirst=False, iterator=False,chunksize=None,compression='infer',thousands=None,decimal=b'.', lineterminator=None,quotechar='"',quoting=0,escapechar=None,comment=None, encoding=None,dialect=None,tupleize_cols=False,error_bad_lines=True,warn_bad_lines=True, skipfooter=0,skip_footer=0,doublequote=True,delim_whitespace=False,as_recarray=False, compact_ints=False,use_unsigned=False,low_memory=True,buffer_lines=None, memory_map=False,float_precision=None)

Read general delimited file into DataFrame

Also supports optionally iterating or breaking of the file

into chunks.

Additional help can be found in theonline docs for IO Tools.

(2)pandas.crosstab(index,columns,values=None,rownames=None,colnames=None,

      aggfunc=None,margins=False,margins_name='All',dropna=True,normalize=False)

Compute a simple cross-tabulation of two (or more) factors. By default

computes a frequency table of the factors unless an array of values and an

aggregation function are passed


15259227-b0676a6a0545f074.png
图10-6(2):示例1

:crosstab的前两个参数可是数组、Series或数组的列表

示例2:回到之前上一数据透视表研究的小费数据集,在小费数据集中操作(见图10-7)

15259227-fa89ff09c31223ae.png
图10-7:示例2

猜你喜欢

转载自blog.csdn.net/weixin_34292287/article/details/87231597