2017-02-22 40 views
1

我試圖從對角線軸的數據框獲得平均意味着在對角線軸在熊貓

  2015-08-31 2015-09-30 2015-10-31 2015-11-30 2015-12-31 \ 
createdat                 
2015-08-31 1.333333 12.555556 10.444444 5.888889 5.888889 
2015-09-30 0.000000 6.777778 4.111111 1.000000 5.333333 
2015-10-31 0.000000 0.000000 5.000000 12.312500 9.937500 
2015-11-30 0.000000 0.000000 0.000000 1.909091 14.000000 
2015-12-31 0.000000 0.000000 0.000000 0.000000 6.760000 

所以實際上我想獲得的1.333333 + 6.777778 + 5.000000 1.909091平均

和隨後的12.555556平均值+ 4.111111 + 12.312500

如何實現這一目標?

回答

1

只需使用np.diag。對於主對角線,這簡直是

np.diag(df).mean() 

,您可以高於或低於主對角線轉移與k參數。

如果你決心要拿到說,所有主對角線的,你可以只適用的東西同樣的做法一樣

{i: np.diag(df, i).mean() for i in range(-1*(df.shape[0]-1), df.shape[1])} 

演示

>>> df 
    0 1 2 
0 6 1 7 
1 4 9 8 
2 0 3 9 

>>> np.diag(df).mean() 
8.0 

>>> np.diag(df, k=1).mean() 
4.5 

>>> {i: np.diag(df, i).mean() for i in range(-1*(df.shape[0]-1), df.shape[1])} 
{-2: 0.0, -1: 3.5, 0: 8.0, 1: 4.5, 2: 7.0}