2017-07-28 157 views
1

我想在熊貓中創建一個有條件的列以及之前的值和其他列。熊貓自我條件列

import pandas as pd 
import numpy as np 
a = np.random.standard_normal(100) 
A = pd.DataFrame(a) 
A['Out'] = 0 
A['Out2'] = 0 
for t in range(1,A.shape[0]): 
    if (A[0][t] > 1) & (A['Out'][t-1]==0): 
     A['Out'][t] = 1 
    elif (A[0][t] < -1) & (A['Out'][t-1]==0): 
     A['Out'][t] = -1 
    elif ((A[0][t] > 0) & (A['Out'][t-1]==-1)) | ((A[0][t] < 0) & (A['Out'][t-1]==1)): 
     A['Out'][t] = 0 
    else: 
     A['Out'][t] = A['Out'][t-1] 
A['Out2'] = np.where((A.index== 0),0 
     ,np.where((A[0] > 1) & (A['Out2'].shift()==0), 1 
     ,np.where((A[0] < -1) & (A['Out2'].shift()==0), -1 
     ,np.where(((A[0] > 0) & (A['Out2'].shift()==-1)) | ((A[0] < 0) & (A['Out2'].shift()==1)), 0 
     ,A['Out2'].shift())))) 

列A ['Out2']試圖以向量化形式複製A ['Out'],但不讀取以前的值。列A ['Out']花費很長時間才能通過循環進行編譯。有人能以更快,矢量化的方式幫助我創建此專欄嗎?

+1

你能提供您所需的輸出和輸入的例子? – asongtoruin

回答

1

您可以創建一個函數,然後使用apply。要訪問以前的數據,您可以使用一個變量來存儲該值。希望以下代碼有所幫助。

import pandas as pd 
import numpy as np 
a = np.random.standard_normal(100) 
A = pd.DataFrame(a) 
state = 0 
def get_val(A,prev_state): 
    global state 
    if (A > 1) & (prev_state==0): 
     state = 1 
    elif (A < -1) & (prev_state==0): 
     state = -1 
    elif ((A > 0) & (prev_state==-1)) | ((A < 0) & (prev_state==1)): 
     state = 0  
    return state 

A['Out'] = A[0].apply(lambda x: get_val(x,state)) 

輸出:

 
      0 Out 
0 1.366864 1  
1 0.887763 1  
2 -0.663636 0  
3 -1.824950 -1  
4 0.459663 0  
5 -1.325129 -1  
6 1.587188 0  
7 -0.148159 0  
8 0.578862 0  
9 0.758460 0  

如果使用%%timeit

100 loops, best of 3: 2.16 ms per loop 
+0

這是完美的...感謝您的快速反應! –

+0

不客氣@random_black。當你獲得足夠的聲望時,不要忘記加註 – Dark