2016-03-09 24 views
1

任何人都可以告訴我如何更有效地使用熊貓,目前我正在做以下找出兩個項目的相關性,但這不是很快。填充蟒蛇數組沒有雙循環

for i in range(0, df.shape[0]): 
    for j in range(0, df.shape[0]): 
     if i<j: 
      ## get the weights 
      wgt_i = dataWgt_df.ix[df.index[i]][0] 
      wgt_j = dataWgt_df.ix[df.index[j]][0] 
      ## get the std's 
      std_i = dataSTD_df.loc[date][df.index[i]][0] 
      std_j = dataSTD_df.loc[date][df.index[j]][0] 
      ## get the corvariance 
      #print(cor.ix[df.index[i]][df.index[j]]) 
      cor = corr.ix[df.index[i]][df.index[j]] 
      ## create running total 
      totalBottom = totalBottom + (wgt_i * wgt_j * std_i * std_j) 
      totalTop = totalTop + (wgt_i * wgt_j * std_i * std_j * cor) 

我想要做的就是創建一個單位矩陣這樣

0 1 1 1 1 
0 0 1 1 1 
0 0 0 1 1 
0 0 0 0 1 
0 0 0 0 0 

,我就可以用它來繁衍在各種dataframes,wgt_i wgt_j std_i std_j這將爲頂部的數據幀和然後我可以使用求和函數求和得到結果。

這裏我的主要問題是如何快速創建標識數據框,然後創建wgt_i等數據框,因爲其餘部分是相對直接的。

+1

的身份矩陣包含1個主對角線和0其他任何地方。 –

+0

我不是線性代數的專家,但我可以告訴它絕對不是一個單位矩陣... – Ian

回答

0

我不是pandas專家,但它似乎很適合numpy。按照這個假設,這裏有幾件事你可以用numpy來避免雙重嵌套循環。

  1. 伊恩是正確的;這不是一個身份矩陣。如果您想要一個單位矩陣,你可以簡單地使用numpy.identity

    import numpy 
    numpy.identity(5) 
    
    array([[ 1., 0., 0., 0., 0.], 
         [ 0., 1., 0., 0., 0.], 
         [ 0., 0., 1., 0., 0.], 
         [ 0., 0., 0., 1., 0.], 
         [ 0., 0., 0., 0., 1.]]) 
    
  2. 但是,如果你想你上面指定的確切矩陣,可以使用numpy.eye

    
    import numpy 
    n = 5 # yields a 5x5 array; adjust to whatever size you want 
    numpy.sum(numpy.eye(n, k=i) for i in range(1,n)) 
    
    array([[ 0., 1., 1., 1., 1.], 
         [ 0., 0., 1., 1., 1.], 
         [ 0., 0., 0., 1., 1.], 
         [ 0., 0., 0., 0., 1.], 
         [ 0., 0., 0., 0., 0.]]) 
    
+0

謝謝,爲可怕地使用術語道歉,我知道它不是一個單位矩陣,但該解決方案是偉大的! – bpython

+0

@bpython沒問題!如果您喜歡答案,請將其標記爲正確的答案。或者如果你更喜歡它,選擇另一個。 =) – larsbutler

0

這不像來自@larsbutler的解決方案那麼簡短,但是對於大的n更快:

import numpy as np 

n = 5 
M = np.zeros((n,n)) 
M[np.triu_indices_from(M)] = 1 
M[np.diag_indices_from(M)] = 0 

給出:

array([[ 0., 1., 1., 1., 1.], 
     [ 0., 0., 1., 1., 1.], 
     [ 0., 0., 0., 1., 1.], 
     [ 0., 0., 0., 0., 1.], 
     [ 0., 0., 0., 0., 0.]]) 
+0

非常感謝! – bpython