如何使用Python和Pandas将dataframe中的值与其他行中的值进行比较
因此,我有一个列数为的dataframe,基本上是以下结构:如何使用Python和Pandas将dataframe中的值与其他行中的值进行比较,python,pandas,Python,Pandas,因此,我有一个列数为的dataframe,基本上是以下结构: Date Low High Close Position Stop_loss Take_profit Return 21.03 0.234 0.235 0.234 Long 0.23 0.238 0,01709401709 22.03 0.232 0.237 0.235 23.04 0.235 0
Date Low High Close Position Stop_loss Take_profit Return
21.03 0.234 0.235 0.234 Long 0.23 0.238 0,01709401709
22.03 0.232 0.237 0.235
23.04 0.235 0.239 0.238
如果
position==“Long”
它必须采取止损
和获利
并将其与下一行的低
和高
列进行比较。如果中的值获取利润
您能否编辑您的问题以准确反映您的问题?目前还不是很清楚。如果你能添加你得到的任何堆栈跟踪,那也会很有帮助。我试过了,希望能有帮助
def func(row):
if 'Long' in row['Position']:
if (row['Take_profit'] <= row['high'].shift(1)) & (row['Stop_loss'] < row['Low'].shift(1)):
return ((row['Take_profit']/row['Close'])-1)
elif (row['Stop_loss'] >= row['Low'].shift(1)) & (row['Take_profit'] >
row['High'].shift(1)):
return ((row['Stop_loss']/row['Close'])-1)
#this condition if hit both stop loss and take profit:
else:
return null
df['Returns'] = df[df['Position'].isnull() == False].apply(func,axis =1)