I have a dataframe with two conditions. I want to count the rows from when condtion 1 is first time hit until condition 2 is hit, then start over again and wait for the next time cond1 gets hit again and sum up til cond2
What i want to sum is the the "change" column in that span of rows between the conditions.
cond 1 indexes are = 4, 8, 12, 16
cond 2 indexes are = 10, 16, 19, 23
To sum it up i want to sum the change column from index 4 to index 10 skipping index 8, then from 12 to 16, then 16 to 19 and so forth.
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
dfA = pd.DataFrame(randn(100,2),columns='A B'.split())
dfA['B'] = dfA['B']+10
def analyse(df):
df = df.copy()
#df['change'] = 10 for sake for simplicity this is more logical to test
df['change'] = df.B.pct_change()
df['cond1'] = np.where(df['A'] < -1 ,1,0)
df['cond2'] = np.where(df['B'] > 11, 1,0)
df.dropna(inplace=True)
return df
print(analyse(dfA))
output sample:
A B change cond1 cond2
1 0.000357 9.565909 -0.105097 0 0
2 -0.360938 10.326678 0.079529 0 0
3 0.968598 9.536587 -0.076510 0 0
4 -1.144810 9.565296 0.003010 1 0
5 1.107228 10.781904 0.127190 0 0
...