Numpy's ufunc
s have a reduceat
method which runs them over contiguous partitions within an array. So instead of writing:
import numpy as np
a = np.array([4, 0, 6, 8, 0, 9, 8, 5, 4, 9])
split_at = [4, 5]
maxima = [max(subarray for subarray in np.split(a, split_at)]
I can write:
maxima = np.maximum.reduceat(a, np.hstack([0, split_at]))
Both will return the maximum values in slices a[0:4]
, a[4:5]
, a[5:10]
, being [8, 0, 9]
.
I would like a similar function to perform argmax
, noting that I would only like a single maximum index in each partition: [3, 4, 5]
with the above a
and split_at
(despite indices 5 and 9 both obtaining the maximum value in the last group), as would be returned by
np.hstack([0, split_at]) + [np.argmax(subarray) for subarray in np.split(a, split_at)]
I will post a possible solution below, but would like to see one that is vectorized without creating an index over groups.