I have an array assuming discrete values. For each value, I am interested in how often it is assumed in a row.
For instance, if my array is [5 5 5 5 5 0 0 4 1 1 5 1 1 1 1 1 3 3 3 3 2 2 5 1 1 1 1 1 1 2 2 5]
, then I expect as a result the following dictionary:
{
0: [2],
1: [2, 5, 6],
2: [2, 2],
3: [4],
4: [1],
5: [5, 1, 1, 1]
}
The keys are the discrete values from the array. The value for each key is a list telling me how often the key was hit in a row when it occured.
My (working) approach is this:
def durations_per_occurence(
array: np.ndarray,
max: int, # max == np.max(array)
) -> dict:
durations = {k: [] for k in range(max+1)}
current_key = array[0]
current_duration = 0
for key in array:
if key == current_key:
current_duration += 1
else:
durations[current_key].append(current_duration)
current_key = key
current_duration = 1
durations[current_key].append(current_duration) # last entry
return durations
I am grateful for any advice, but particulary interested in built-in Python functionality to speed up the computation. (I often hear that for
-loops are particularly slow in Python and that one should vectorize computations. Is there a neat vectorization for this particular problem?)