« first day (15 days earlier)      last day (105 days later) » 

3:26 PM
So could you explain the line? It looks like black magic to me^^
 
Hi @mathology
Can you give me a min?
 
sure!
 
thanks!
@mathology Let me put the solution in other way that might be easier for you to understand.
 
That'd be great, thank you!
 
As you know we have the column condition as follows:
m = df['condition']
>>> m
0    False
1     True
2     True
3    False
4     True
5     True
6     True
7    False
Name: condition, dtype: bool
And as per the question statement we have to identify the group of continuous rows where the condition is satisfied.
Now we use cumsum (cumulative summation) on the inverted mask m to identify all such continuous rows
blocks = (~m).cumsum()[m]
>>> blocks
1    1
2    1
4    2
5    2
6    2
Name: condition, dtype: int64
As you can see we have been able to identify the groups of continuous rows where the first group consists of rows with index 1 and 2 while the other group consists of rows with index 4, 5 and 6.
Makes sense?
 
3:38 PM
I don't understand why cumsum does what we want
 
no worries let me explain...
You know how cumsum works?
 
No, I don't sorry :/
 
Consider the array:
arr = np.arange(10)
>>> arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
So after taking the cumsum on this array we get:
>>> arr.cumsum()
array([ 0,  1,  3,  6, 10, 15, 21, 28, 36, 45])
So every element in the new array is the sum of all the previous elements + the current element..got the point?
 
alright, got it
 
Let's invert the boolean mask m using ~, we get:
 
3:44 PM
ah and now we only add +1 if there is a row not satisfying the condition and the sum stays the same if we have consecutive Trues?
 
>>> (~m)
0 True
1 False
2 False
3 True
4 False
5 False
6 False
7 True
Name: condition, dtype: bool
Now using cumsum on this produces:
>>> (~m).cumsum()
0    1
1    1
2    1
3    2
4    2
5    2
6    2
7    3
Name: condition, dtype: int64
But we are only interested in the true values in condition so we filter this cumsum result using mask m:
blocks = (~m).cumsum()[m]
>>> blocks
1    1
2    1
4    2
5    2
6    2
Name: condition, dtype: int64
Makes sense?
 
yep!
 
great! now you can simply group the column value on these blocks and aggregate using np.ptp to get the desired result.
 
but where do we take the differences?
 
So np.ptp does that job for us.
np.ptp = `last value in the group` - `first value in the group`
 
3:49 PM
ah ok perfect, now I got it
thank you very much for your time!
 
Glad i could help :)
 

« first day (15 days earlier)      last day (105 days later) »