首页 文章

数据透视表小计

提问于
浏览
0

我有一个数据框:

product = DataFrame({'_product': ['shoes','dress','cap','shoes','purse','t-shirt','t-shirt','dress','t-shirt'], 
             'city': ['A','A','A','B','A','A','B','C','A'],
             'color':['red','black','black','white','black','green','white','yellow','blue'],
             'size':['36','S','M','40','-','L','L','M','S'],
             'param1':['x0001','x0008','x0006','x0002','x0001','x0009','x0011','x0003','x0001'],
             'param2':[23,1,367,689,35,97,100,44,15],
             'param3':['f1','t1','u7','f1','r4','f2','f2','t2','f4'],
             'counter':[1,1,1,1,1,1,1,1,1]})

table=product[['_product','city','color','size','param1','param2','param3','counter']]

应用

pivot_product=pivot_table(table,values=['counter'],rows=['_product','city','color','size','param1','param2','param3'],aggfunc=[np.sum],fill_value=0,margins=True)

我得到一个只有Grand Total行的数据透视表(“All”) .

这是一个假设的样本,实际上我导入了一个包含10万行和20列的表 .

!我绝对有必要在产品级别上进行小计 .

是否有任何有效的方法可以将带有小计的行插入此表中,就像使用字段设置>布局和打印>“以表格形式显示项目标签”的Excel数据透视表一样?

1 回答

  • 1

    我不熟悉Excel中的这个操作,但这里只是按产品计算小计的单行程序 .

    In [43]: pivot_product['subtotals'] = pivot_product[('sum', 'counter')].groupby(level=0).transform(np.sum)
    
    In [44]: pivot_product
    Out[44]: 
                                                        sum  subtotals
                                                    counter           
    _product city color  size param1 param2 param3                    
    cap      A    black  M    x0006  367    u7            1          1
    dress    A    black  S    x0008  1      t1            1          2
             C    yellow M    x0003  44     t2            1          2
    purse    A    black  -    x0001  35     r4            1          1
    shoes    A    red    36   x0001  23     f1            1          2
             B    white  40   x0002  689    f1            1          2
    t-shirt  A    blue   S    x0001  15     f4            1          3
                  green  L    x0009  97     f2            1          3
             B    white  L    x0011  100    f2            1          3
    All                                                   9          9
    

    可能是你想 np.size 我使用 np.count ,具体取决于'counter'列的含义 .

相关问题