2013-04-01 114 views
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) 

我得到一個數據透視表,只有總計行( 「全部」)。

這是一個假設的樣本,實際上我導入了一個有100 000行和20列的表格。

!!對我來說,在產品層面上有小計是絕對必要的。

是否有任何有效的方法來將具有小計的行插入到此表中,就像Excel數據透視表中的字段設置>佈局&打印>「以表格形式顯示項目標籤」允許做什麼?

+0

你想在什麼語言中執行樞軸? – Taryn

+0

@bluefeet:python – user2233035

+1

看看這個:http://stackoverflow.com/questions/15570099/pandas-pivot-tables-row-subtotals/15574875 – herrfz

回答

0

我對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,根據「計數器」列是什麼意思。

+0

謝謝,這是我需要的解決方案。 – user2233035