Pandas:透视表(pivotTab)和交叉表(crossTab)

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

一、透视表(pivotTab)

透视表就是将指定原有DataFrame的列分别作为行索引和列索引,然后对指定的列应用聚集函数(默认情况下式mean函数)。

df = DataFrame({'类别':['水果','水果','水果','蔬菜','蔬菜','肉类','肉类'],
                '产地':['美国','中国','中国','中国','新西兰','新西兰','美国'],
                '水果':['苹果','梨','草莓','番茄','黄瓜','羊肉','牛肉'],
               '数量':[5,5,9,3,2,10,8],
               '价格':[5,5,10,3,3,13,20]})
print(df)
    产地  价格  数量  水果  类别
0   美国   5   5  苹果  水果
1   中国   5   5   梨  水果
2   中国  10   9  草莓  水果
3   中国   3   3  番茄  蔬菜
4  新西兰   3   2  黄瓜  蔬菜
5  新西兰  13  10  羊肉  肉类
6   美国  20   8  牛肉  肉类

1.按‘产地’和‘类别’重新索引,然后在‘价格’和‘数量’上执行mean函数

print(df.pivot_table(index=['产地','类别']))
          价格    数量
产地  类别            
中国  水果   7.5   7.0
    蔬菜   3.0   3.0
新西兰 肉类  13.0  10.0
    蔬菜   3.0   2.0
美国  水果   5.0   5.0
    肉类  20.0   8.0
print(df.pivot_table(columns=['产地','类别']))
    产地   类别
价格  中国   水果     7.5
         蔬菜     3.0
    新西兰  肉类    13.0
         蔬菜     3.0
    美国   水果     5.0
         肉类    20.0
数量  中国   水果     7.0
         蔬菜     3.0
    新西兰  肉类    10.0
         蔬菜     2.0
    美国   水果     5.0
         肉类     8.0
dtype: float64

2.行索引为‘产地’,列索引为‘类别’,

对‘价格’应用‘max’函数,并提供分项统计,缺失值填充0

print(df.pivot_table('价格',index='产地',columns='类别',aggfunc='max',margins=True,fill_value=0))
类别     水果    肉类   蔬菜   All
产地                        
中国   10.0   0.0  3.0  10.0
新西兰   0.0  13.0  3.0  13.0
美国    5.0  20.0  0.0  20.0
All  10.0  20.0  3.0  20.0

二、交叉表(crossTab)

交叉表是用于统计分组频率的特殊透视表

print(pd.crosstab(df['类别'],df['产地'],margins=True)) # 按类别分组,统计各个分组中产地的频数
产地   中国  新西兰  美国  All
类别                   
水果    2    0   1    3
肉类    0    1   1    2
蔬菜    1    1   0    2
All   3    2   2    7

猜你喜欢

转载自blog.csdn.net/bqw18744018044/article/details/80015840