Trend of boolen column

The complete code is:

import pandas as pd
import numpy as np

df = pd.read_excel('C:/Users/Administrator/Documents/Book1.xlsx')

df['boolean'] = df['Prev Close'] < df['Close']

#sample data
df = pd.DataFrame({'boolean' : [False] + [True] + [False] * 2 +
                               [True] * 3 + [False] + [True]})
    
print (df)
   boolean
0    False
1     True
2    False
3    False
4     True
5     True
6     True
7    False
8     True

How to check how many true values are there in succession if there are multiple true values add 1 to the Trending Counter and append it as a column. For false values counter has to be set as 0

Hence the final expected dataframe will look as shown:

   boolean  trend
0    False      0
1     True      1
2    False      0
3    False      0
4     True      1
5     True      2
6     True      3
7    False      0
8     True      1

Answer

For trend use:

a = df['boolean']
b = a.cumsum()
df['trend'] = (b-b.mask(a).ffill().fillna(0).astype(int))

   boolean  trend
0    False      0
1     True      1
2    False      0
3    False      0
4     True      1
5     True      2
6     True      3
7    False      0
8     True      1

Details:

First use Series.cumsum:

print (a.cumsum())
0    0
1    1
2    1
3    1
4    2
5    3
6    4
7    4
8    5
Name: boolean, dtype: int32

Then replace Trues for NaNs and forward filling missing values:

print (b.mask(a).ffill())
0     0.0
1     0.0
2     0.0
3     0.0
4     2.0
5     2.0
6     2.0
7     2.0
8     2.0
9     5.0
10    5.0
Name: boolean, dtype: float64

Then subtract values b:

print (b-b.mask(a).ffill())
0     0.0
1     0.0
2     1.0
3     2.0
4     0.0
5     0.0
6     1.0
7     2.0
8     3.0
9     0.0
10    1.0
Name: boolean, dtype: float64