Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

python - Pandas: update a column with an if statement

My current dataframe looks like this:

    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

What I tried is the following: 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')

So update the column action with buy if three times in a row the values of the column difference is smaller than it's previous value. Any idea on how to proceed? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you need:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...