Issue
I'm trying to count the number of True values in a numpy.array
until a False is reached.
For example, if you have
condition = np.array([True, True, True, False,
False, True, False, True, True, False, True])
Then the desired result would be
np.array([3, 2, 1, 0, 0, 1, 0, 2, 1, 0, 1])
Edit:
Numpy first occurrence of value greater than existing value is not what I'm asking because that's asking about the first time a condition is satisfied. I'm asking how many times in a row a condition is satisfied each time it is satisfied. Find first sequence item that matches a criterion also doesn't work because, again, I'm not asking about the first time a sequence satisfied a condition.
Solution
Line by line to explain the calculation
import numpy as np
condition = np.array([True, True, True, False, False, True, False, True, True, False, True])
rvs = condition[::-1] # Reverse the array order
rvs
# array([ True, False, True, True, False, True, False, False, True,
True, True])
cum_rvs = rvs.cumsum() # Cumulative sum of Trues
cum_at_zero = (~rvs)*cum_rvs # Cum where rvs is True set to zero
cum_max = np.maximum.accumulate( cum_at_zero ) # Equivalent to cummax( cum_at_zero )
cum_max
# array([0, 1, 1, 1, 3, 3, 4, 4, 4, 4, 4])
result = cum_rvs - cum_max # Use cum_max to adjust the cum_rvs down
result = result[::-1] # Reverse the result order
result
# array([3, 2, 1, 0, 0, 1, 0, 2, 1, 0, 1])
Or in more condensed form:
rvs = condition[::-1]
cum_rvs = rvs.cumsum()
result = ( cum_rvs - np.maximum.accumulate((~rvs)*cum_rvs ))[::-1]
Answered By - Tls Chris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.