[英]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
如果您知道如何使這項工作變得更快,我將不勝感激! 謝謝!
編輯:
所需 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
您是否希望轉而使用“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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.