Home > OS >  How can I change logic from (True to False) or (False to True) based on the condition in dataframe
How can I change logic from (True to False) or (False to True) based on the condition in dataframe

Time:01-08

I would like to trigger the column contain Boolean back and forth based on the condition from another column. The idea is to determine the safe zone to (or not) to take action

For instance... based on the condition in "Check", if true change logic in "Skip"

df_ohlcv["Check"] = ...Condition...
df_ohlcv["Skip"] = df_ohlcv["Skip"].where(~df_ohlcv["Check"], ~df_ohlcv["Skip"])

The code above I got KeyError: 'Skip'. I guess because the 'Skip' is not initiallised prior to be used. If I assign some value (for example False) then 'Skip' cannot keep the previous logic (Stuck at False)

I would like to have the result as following

Check Skip
False False
False False
False False
True True
False True
False True
False True
True False
False False
False False
False False
True True
False True
False True

CodePudding user response:

df["Skip"] = df["Check"].cumsum().mod(2).astype(bool)
  • take the cumulative sum of the True/False "Check" column
    • because True == 1 and False == 0, this will decide the groups as 0, 1, 2, 3...
  • take the modulo 2 of the groups to reduce them to 0, 1, 0, 1...
  • then boolify for the 0 -> False, 1 -> True mapping

to get

>>> df

    Check   Skip
0   False  False
1   False  False
2   False  False
3    True   True
4   False   True
5   False   True
6   False   True
7    True  False
8   False  False
9   False  False
10  False  False
11   True   True
12  False   True
13  False   True

CodePudding user response:

If I got you right:

import numpy as np
df_ohlcv["Skip"] = np.where(df_ohlcv["Check"], (1-df_ohlcv["Skip"]).astype(bool), df_ohlcv["Skip"])

This will change 'skip' to its opposite in every row that 'check' is True

  • Related