3 回答

TA貢獻1847條經驗 獲得超11個贊
感謝您添加數據和示例輸出。首先,我很確定您不能對它進行矢量化處理,因為每個計算都取決于上一個的輸出。所以這是我所能做到的最好的。
您的方法大約0.116999在我的機器上幾秒鐘
這個大約在0.0039999幾秒鐘之內
沒有向量化,但是速度得到了很好的提高,因為為此使用列表并將其添加回末尾的數據幀更快。
def myfunc(pos_pre, signal):
if signal == 0: # if the signal is negative
# if the new col value above -0.2 is > -1 then subtract 0.2 from that value
pos = pos_pre - 0.02
if pos < -1: # if the row above - 0.2 < -1 set the value of current row to -1
pos = -1
elif signal == 1:
# if the row above + 0.2 < 1 then add 0.2 to the value of the current row
pos = pos_pre + 0.02
if pos > 1: # if the value above + 0.1 > 1 set the current row to 1
pos = 1
return pos
''' set first position value because you aren't technically calculating it correctly in your method since there is no
position minus 1... IE: it will always be 0.02'''
new_pos = [0.02]
# skip index zero since there is no position 0 minus 1
for i in range(1, len(df)):
new_pos.append(myfunc(pos_pre=new_pos[i-1], signal=df['signal'].iloc[i]))
df['position'] = new_pos
輸出:
df.position
0 0.02
1 0.04
2 0.06
3 0.08
4 0.10
5 0.12
6 0.14
7 0.16
8 0.18

TA貢獻1806條經驗 獲得超8個贊
不要使用循環。熊貓專門從事矢量化運算,例如signal == 0:
pos_shift = df['position'].shift() - 0.02
m1 = df['signal'] == 0
m2 = pos_shift < -1
df.loc[m1 & m2, 'position'] = -1
df['position'] = np.where(m1 & ~m2, pos_shift, df['position'])
您可以為編寫類似的內容signal == 1。

TA貢獻1898條經驗 獲得超8個贊
有很多更好的方法,但是這種方法也應該起作用:
df['previous'] = df.signal.shift()
def get_signal_value(row):
if row.signal == 0:
compare = row.previous - 0.02
if compare < -1:
return -1
else:
return compare
elif row.signal == 1:
compare = row.previous + 0.01
if compare > 1:
return 1
else:
return compare
df['new_signal'] = df.apply(lambda row: get_signal_value(row), axis=1)
添加回答
舉報