[英]Selecting rows where column value is 1 in the current row, but 0 in the previous row
I am working with a DataFrame on Python 3.8 where I try to replicate Excel calculations - a basic if
with two criteria, one of which is referencing itself a row before.我正在使用 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
The second criterion seems to be completely ignored... as trade_price
should have only one 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
If you have any idea how to make this work and also make it faster I'd really appreciate it!如果您知道如何使这项工作变得更快,我将不胜感激! Thanks!
谢谢!
EDIT:编辑:
Required output:所需 output:
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
Are you looking to shift on "z_en_crit" instead?您是否希望转而使用“z_en_crit”? Also, you should reverse the direction of the shift if you want to match on the first of the group, not the last.
此外,如果要匹配组的第一个而不是最后一个,则应反转移位的方向。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.