I am trying to calculate how often a condition is entered and how long it lasts. For example, I have three possible states 1,2 and 3, the state of which is registered in the pandas Dataframe:
test = pd.DataFrame([2,2,2,1,1,1,2,2,2,3,2,2,1,1], index=pd.date_range('00:00', freq='1h', periods=14))
For example, state 1 is entered twice (at index 3 and 12), the first time it lasts three hours, the second time two hours (so on average 2.5). State 2 is administered 3 times, an average of 2.66 hours.
I know that I can mask data that I'm not interested in, for example, to analyze state 1:
state1 = test.mask(test!=1)
but from there I canβt find a way to continue.
source share