Home > Software design >  How to satisfy the condition of 2 columns different rows at the same time
How to satisfy the condition of 2 columns different rows at the same time

Time:07-10

My logic is like this:

cond2 column is true before expected column, and cond1 column is true before cond2 column, then expected column can be true

input

import pandas as pd
import numpy as np
d={'cond1':[False,False,True,False,False,False,False,True,False,False],'cond2':[False,True,False,True,True,False,False,False,True,False]}
df = pd.DataFrame(d)

expected result table

    cond1   cond2   expected
0   FALSE   FALSE   
1   FALSE   TRUE    
2   TRUE    FALSE   
3   FALSE   TRUE    
4   FALSE   TRUE    
5   FALSE   FALSE   TRUE
6   FALSE   FALSE   TRUE
7   TRUE    FALSE   
8   FALSE   TRUE    
9   FALSE   FALSE   TRUE

CodePudding user response:

The description is not fully clear. It looks like you need a cummax per group starting with True in cond1:

m = df.groupby(df['cond1'].cumsum())['cond2'].cummax()

df['expected'] = df['cond2'].ne(m)

Output:

   cond1  cond2  expected
0  False  False     False
1  False   True     False
2   True  False     False
3  False   True     False
4  False   True     False
5  False  False      True
6  False  False      True
7   True  False     False
8  False   True     False
9  False  False      True

CodePudding user response:

It's not very clear what you're looking for~

df['expected'] = ((df.index > df.idxmax().max())
                  & ~df.any(axis=1))

# Output:

   cond1  cond2  expected
0  False  False     False
1  False   True     False
2   True  False     False
3  False   True     False
4  False   True     False
5  False  False      True
6  False  False      True
7   True  False     False
8  False   True     False
9  False  False      True
  • Related