python - Pandas:使用 if 语句更新列

标签 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')

因此更新列 actionbuy如果连续三次列的值 difference小于它以前的值。关于如何进行的任何想法?谢谢!

最佳答案

我认为你需要:

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

关于python - Pandas:使用 if 语句更新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54627750/

相关文章:

python - 是否真的有必要对比较相同的类进行哈希处理?

python - 如何使用 doctest 检查程序是否产生了某些输出?

python - 在 falcon Python 中分隔路由的正确方法是什么?

Python:使用基于嵌套列表中唯一值的列创建 Pandas 数据框

python Pandas : set row and col to zeros if element is zero

python - 使用 pytest 同时运行 celery 任务

python - 如何从python中的MySQL选择列表中删除括号以通过变量值比较列表数据

python - 通过/失败数据帧示例

python - 将未知大小列表的列表拆分为 n 号的数据框。列数

python - 旋转子数据框