2017-05-28 37 views
0

我有一個數據幀,價格Df的:熊貓據幀 - 當前行下搶值x行和比較

Close_x 
 
2121.25 
 
2119.25 
 
2119.5 
 
2115.25 
 
2120 
 
2118 
 
2115.25 
 
2116.25 
 
2116.25

如果第一Close_x值(2121.25)比Close_x更大值9行向下(2116.25),我希望有一個新的列,「利潤」增加100象下面這樣:

Df['Profit'] = '' 

for index, row in Df.iterrows(): 
    if Df['Close_x'].shift(9) > Df['Close_x']: 
     Df['Profit'] == 100 
    else: 
     Df['Profit'] == -100 

我也試過這樣:

for index, row in Df.iterrows(): 
    if Df['Close_x'] + 9 > Df['Close_x']: 
     Df['Profit'] == 100 
    else: 
     Df['Profit'] == -100 

對於這兩種嘗試,我得到以下錯誤:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

請注意,我有成千上萬的Close_x行的,所以我需要此基礎上進行了一些規則,如「9行從下到迭代當前值「而不是調用特定片段,如[:9]。

回答

1

看來你需要numpy.where

N = 3 
Df['Profit'] = np.where(Df['Close_x'].shift(3) > Df['Close_x'], 100, -100) 
Df.loc[Df.index < N,'Profit'] = np.nan  
print (Df) 
    Close_x Profit 
0 2121.25  NaN 
1 2119.25  NaN 
2 2119.50  NaN 
3 2115.25 100.0 
4 2120.00 -100.0 
5 2118.00 100.0 
6 2115.25 -100.0 
7 2116.25 100.0 
8 2116.25 100.0 

或許需要:

N = 3 
for index,row in Df.iterrows(): 
     if index < N: 
      continue 
     if(Df.loc[index-N, 'Close_x'] > Df.loc[index, 'Close_x']): 
      Df.loc[index, 'Profit'] = 100 
     else: 
      Df.loc[index, 'Profit'] = -100    
print (Df) 
    Close_x Profit 
0 2121.25  NaN 
1 2119.25  NaN 
2 2119.50  NaN 
3 2115.25 100.0 
4 2120.00 -100.0 
5 2118.00 100.0 
6 2115.25 -100.0 
7 2116.25 100.0 
8 2116.25 100.0 
+0

嘿,感謝您的幫助。我確實希望將利潤保持在+100或-100,不要因爲價格變化而關心實際利潤,而只需要價格更高或更低時的二元+100或-100。我現在正在處理這個循環。是的,我需要使用祿函數,而不是我在做什麼... –

+0

不幸的是,我從來沒有與財務工作,所以對我來說很難回答。但嘗試編輯答案。 – jezrael

+0

完美!非常感謝! –

0
for index, row in Df.iterrows(): 
    if Df['Close_x'].shift(9) > Df['Close_x']: 
     Df['Profit'] == 100 
    else: 
     Df['Profit'] == -100 

你遍歷你的數據框卻一次也沒有使用變量索引和行?這似乎不正確