在Python中优化while循环

时间:2019-03-20 09:04:51

标签: python pandas dataframe

我有一段代码需要永远运行。有人知道如何优化它吗?

该公式的目的是创建一个执行以下操作的列:when 'action' != 0, if 'PX_LAST'<'ma', populate 'buy_sell' with -1, if 'PX_LAST'>'ma', populate 'buy_sell' with 1;在其他情况下,请勿使用新值填充“ buy_sell”。

Fyi-列“ action”中填充了0或1

#create column
df_zinc['buy_sell'] = 0
index = 0

while index < df_zinc.shape[0]:
    if df_zinc['action'][index] != 0:
        continue
        if df_zinc['PX_LAST'][index]<df_zinc['ma'][index]:
            df_zinc.loc[index,'buy_sell'] = -1
        elif df_zinc['PX_LAST'][index]>df_zinc['ma'][index]:
            df_zinc.loc[index,'buy_sell'] = 1
    else:
        index = index + 1

1 个答案:

答案 0 :(得分:0)

我认为您需要:

import numpy as np

mask1 = df_zinc['action'] != 0
mask2 = df_zinc['PX_LAST'] < df_zinc['ma']
mask3 = df_zinc['PX_LAST'] > df_zinc['ma']

df_zinc['buy_sell'] = np.select([mask1 & mask2, mask1 & mask3], [-1,1], 0)