熊猫:使用if语句更新列(np.select)

时间:2019-02-11 09:49:17

标签: python pandas

我当前的数据框如下:

    midprice    ema12   ema26   difference
0   0.002990    0.002990    0.002990    0.000000e+00
1   0.002990    0.002990    0.002990    4.227920e-08
2   0.003018    0.002994    0.002992    2.295777e-06
3   0.003025    0.002999    0.002994    4.579221e-06
4   0.003067    0.003009    0.003000    9.708765e-06
5   0.003112    0.003025    0.003008    1.718520e-05

我尝试的是以下内容: df.loc[:, 'action'] = np.select(condlist=[df.difference[0] < df.difference[-1] < df.difference[-2], df.ema12 < df.ema26 ], choicelist=['buy', 'sell'], default='do nothing')

因此,如果连续三次action列的值小于之前的值,请用buy更新difference列。对如何进行有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:4)

我认为您需要:

m1= df['difference'] < df['difference'].shift(-1)
m2= df['difference'] < df['difference'].shift(-2)
m3= df['difference'] < df['difference'].shift(-3)

df['action'] = np.select(condlist=[m1 | m2 | m3, df.ema12 < df.ema26 ], 
                         choicelist=['buy', 'sell'], 
                         default='do nothing')
print (df)
   midprice     ema12     ema26    difference      action
0  0.002990  0.002990  0.002990  0.000000e+00         buy
1  0.002990  0.002990  0.002990  4.227920e-08         buy
2  0.003018  0.002994  0.002992  2.295777e-06         buy
3  0.003025  0.002999  0.002994  4.579221e-06         buy
4  0.003067  0.003009  0.003000  9.708765e-06         buy
5  0.003112  0.003025  0.003008  1.718520e-05  do nothing