中文标题:数据透视表小计

2024-09-29 23:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

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']]

申请

^{pr2}$

我得到一个只包含总计行(“All”)的透视表。在

这是一个假设的示例,实际上我导入了一个包含10万行和20列的表。在

!!对我来说,在产品级别上有小计是绝对必要的。在

是否有任何有效的方法可以将包含小计的行插入此表中,就像具有字段设置的Excel数据透视表gt;Layout&Print>;“以表格形式显示项目标签”所允许的那样?在


Tags: 数据citysizeproductcolorf1param1black
1条回答
网友
1楼 · 发布于 2024-09-29 23:27:26

我不熟悉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'列的含义。在

相关问题 更多 >

    热门问题