Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas True False Matching

For this table:

enter image description here

I would like to generate the 'desired_output' column. One way to achieve this maybe:

  1. All the True values from col_1 are transferred straight across to desired_output (red arrow)
  2. In desired_output, place a True value above any existing True value (green arrow)

Code I have tried:

df['desired_output']=df.col_1.apply(lambda x: True if x.shift()==True else False)

Thankyou

like image 631
Angus Stevenson Avatar asked Jan 25 '23 19:01

Angus Stevenson


1 Answers

You can chain by | for bitwise OR original with shifted values by Series.shift:

d = {"col1":[False,True,True,True,False,True,False,False,True,False,False,False]}
df = pd.DataFrame(d)

df['new'] = df.col1 | df.col1.shift(-1)
print (df)
     col1    new
0   False   True
1    True   True
2    True   True
3    True   True
4   False   True
5    True   True
6   False  False
7   False   True
8    True   True
9   False  False
10  False  False
11  False  False
like image 61
jezrael Avatar answered Mar 15 '23 08:03

jezrael