Pandas学习笔记八——数据透视表

数据透视表

数据透视表是一种类似于Groupby的操作方法,常见于Excel与类似的表格应用中。数据透视表将每一列作为输入,输出将数据不断细分为多个维度累计信息的二维数据表。数据透视表相比与Groupby操作更像是一种多维的GroupBy累计操作。也就是说,虽然你也可以分割-应用-组合,但是分割和组合不是发生在一维索引上,而是在二维网络上(行和列同时分组)

#示例使用泰坦尼克号的乘客信息
import numpy as np
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset('titanic')

数据透视表语法

#统计不同性别与船舱等级下泰坦尼号乘客的生还情况,累计方法默认使用mean()
titanic.pivot_table('survived', index='sex', columns='class')

#输出结果
class      First    Second     Third
sex                                 
female  0.968085  0.921053  0.500000
male    0.368852  0.157407  0.135447
#pivot_table支持多级索引,数据透视表中的分组可以通过各种参数指定多个等级
#通过pd.cut函数将年龄进行分段

age = pd.cut(titanic['age'], [1,18,80])
titanic.dropna('age').pivot_table('survived', ['sex', age], 'class')

#输出结果
class               First    Second     Third
sex    age                                   
female (18, 80]  0.909091  1.000000  0.511628
       NaN       0.972973  0.900000  0.423729
male   (18, 80]  0.800000  0.600000  0.215686
       NaN       0.375000  0.071429  0.133663

其他数据透视表选项

#DataFrame的pivot_table方法的完整签名如下:
DataFrame.pivot_table(data, value=None, index=None, columns=None, aggfunc='mean',
                      fill_value=None, margins=False,dropna=True, margins_name='All')
  • aggfunc参数用于设置累计函数类型,默认值是mean()。与groupby的用法一样,累计函数可以用一些常见的字符串(‘sum’、’mean‘、’count’、‘min’、‘max’等)表示,也可以是标准的累计函数(np.sum(), np.min(), sum()等)表示。另外还可以通过字典为不同的列指定不同的累计函数。

    titanic.pivot_table(index='sex', columns='class', aggfunc={'survived':sum, 'fare':mean})
    
    
    #输出结果:
    
                fare                       survived             
    class        First     Second      Third    First Second Third
    sex                                                           
    female  106.125798  21.970121  16.118810       91     70    72
    male     67.226127  19.741782  12.661633       45     17    47
  • 当需要计算每一组的总数是,可以通过margins参数来设置,margin的标签可以通过margins_name参数来设置,默认值是’All‘

    titanic.pivot_table('survived', index='sex', columns='class', margins=True)
    
    
    #输出结果:
    
    class      First    Second     Third       All
    sex                                           
    female  0.968085  0.921053  0.500000  0.742038
    male    0.368852  0.157407  0.135447  0.188908
    All     0.629630  0.472826  0.242363  0.383838

猜你喜欢

转载自blog.csdn.net/jasonzhoujx/article/details/81702462