2015-04-02 75 views
4

我想計算每個多指標子水平的總和。然後,將其保存在數據框中。熊貓,計算每個MultiIndex子水平的總和

我目前的數據框的樣子:

    values 
    first second 
    bar one  0.106521 
      two  1.964873 
    baz one  1.289683 
      two -0.696361 
    foo one -0.309505 
      two  2.890406 
    qux one -0.758369 
      two  1.302628 

和所需的結果是:

    values 
    first second 
    bar one  0.106521 
      two  1.964873 
      total 2.071394 
    baz one  1.289683 
      two -0.696361 
      total 0.593322 
    foo one -0.309505 
      two  2.890406 
      total 2.580901 
    qux one -0.758369 
      two  1.302628 
      total 0.544259 
    total one  0.328331 
      two  5.461546 
      total 5.789877 

目前我發現如下因素實現,它的工作原理。但我想知道是否有更好的選擇。我需要儘可能快的解決方案,因爲在某些情況下,當我的數據幀變大時,計算時間似乎需要很長時間。

In [1]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], 
    ...:   ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] 
    ...: 

In [2]: tuples = list(zip(*arrays)) 

In [3]: index = MultiIndex.from_tuples(tuples, names=['first', 'second']) 

In [4]: s = Series(randn(8), index=index) 

In [5]: d = {'values': s} 

In [6]: df = DataFrame(d) 

In [7]: for col in df.index.names: 
    .....:  df = df.unstack(col) 
    .....:  df[('values', 'total')] = df.sum(axis=1) 
    .....:  df = df.stack() 
    .....: 

回答

0

相當難看代碼:

In [162]: 

print df 
       values 
first second   
bar one  0.370291 
     two  0.750565 
baz one  0.148405 
     two  0.919973 
foo one  0.121964 
     two  0.394017 
qux one  0.883136 
     two  0.871792 
In [163]: 

print pd.concat((df.reset_index(), 
       df.reset_index().groupby('first').aggregate('sum').reset_index())).\ 
         sort(['first','second']).\ 
         fillna('total').\ 
         set_index(['first','second']) 
       values 
first second   
bar one  0.370291 
     two  0.750565 
     total 1.120856 
baz one  0.148405 
     two  0.919973 
     total 1.068378 
foo one  0.121964 
     two  0.394017 
     total 0.515981 
qux one  0.883136 
     two  0.871792 
     total 1.754927 

基本上,由於所述附加行中,「總」,需要計算和插入原始數據幀,它是不會被一到原始與結果之間的一種關係,這種關係不是多對一的關係。所以,我認爲你必須分別生成'總'數據框,並且使用原始數據框生成'全部'數據框。

+0

從我所看到的你設法計算總「第一」水平...我的需要涉及更多的水平,每個級別需要一個總數。我會測試你的解決方案,看看時間計算是否有任何改進。 – Iulian 2015-04-02 16:08:16