选择列值在当前行中为 1,但在上一行中为 0 的行
Selecting rows where column value is 1 in the current row, but 0 in the previous row
我在 Python 3.8 上使用 DataFrame,我尝试在其中复制 Excel 计算 - 一个基本的 if
有两个条件,其中一个是在前一行引用自己.
Backtest['trade_price']=0
Backtest.loc[(Backtest['z_en_crit']==1) &
(Backtest['trade_price'].shift(-1)==0), "trade_price"] = 1
第二个标准似乎被完全忽略了...因为 trade_price
应该只有一个 1
z_en_crit trade_price
Datetime
2020-10-21 11:00:00+01:00 0.0 0
2020-10-21 12:00:00+01:00 0.0 0
2020-10-21 13:00:00+01:00 1.0 1
2020-10-21 14:00:00+01:00 1.0 1
2020-10-21 15:00:00+01:00 1.0 1
2020-10-21 16:00:00+01:00 0.0 0
如果您知道如何使它工作并使其更快,我将不胜感激!谢谢!
编辑:
所需输出:
z_en_crit trade_price
Datetime
2020-10-21 11:00:00+01:00 0.0 0
2020-10-21 12:00:00+01:00 0.0 0
2020-10-21 13:00:00+01:00 1.0 1
2020-10-21 14:00:00+01:00 1.0 0
2020-10-21 15:00:00+01:00 1.0 0
2020-10-21 16:00:00+01:00 0.0 0
您是否要改用“z_en_crit”?另外,如果你想匹配组中的第一个而不是最后一个,你应该反转移位的方向。
df['trade_price'] = np.where(
df['z_en_crit'].eq(1) & df['z_en_crit'].shift(1).eq(0), 1, 0)
df
z_en_crit trade_price
Datetime
2020-10-21 11:00:00+01:00 0.0 0
2020-10-21 12:00:00+01:00 0.0 0
2020-10-21 13:00:00+01:00 1.0 1
2020-10-21 14:00:00+01:00 1.0 0
2020-10-21 15:00:00+01:00 1.0 0
2020-10-21 16:00:00+01:00 0.0 0