英文:
How can I change logic from (True to False) or (False to True) based on the condition in dataframe
问题
我想触发基于另一列的条件,交替设置包含布尔值的列。想法是确定是否安全地采取行动。
例如...基于“Check”列中的条件,如果为真,则更改“Skip”列的逻辑
df_ohlcv["Check"] = ...条件...
df_ohlcv["Skip"] = df_ohlcv["Skip"].where(~df_ohlcv["Check"], ~df_ohlcv["Skip"])
上面的代码出现了KeyError: 'Skip'
错误。我猜这是因为在使用之前没有初始化“Skip”列。如果我分配一些值(例如False
),那么“Skip”列无法保持先前的逻辑(保持在False
)。
我想要的结果如下所示:
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 |
英文:
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 |
答案1
得分: 4
df["Skip"] = df["Check"].cumsum().mod(2).astype(bool)
英文:
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
答案2
得分: 1
如果我理解正确:
import numpy as np
df_ohlcv["Skip"] = np.where(df_ohlcv["Check"], (1 - df_ohlcv["Skip"]).astype(bool), df_ohlcv["Skip"])
这将会在每一行中,当"Check"为True时,将"Skip"的值改变为它的相反值。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论