You can do it using np.maximum.reduceat
:
import numpy as np
lst = np.array([[2,6],[1,4],[0,1],[1,1],[2,3],[0,2]])
lst = lst[np.argsort(lst[:,0])] #sorting lst by first row
u, idx = np.unique(lst[:,0], return_index = True)
print(np.c_[u, np.maximum.reduceat(lst[:,1], idx)])
At first array should be sorted. Then you need to get indices that splits array into groups: idx = [0, 2, 4]
and corresponding values of first column u = [0, 1, 2]
. Finally, use np.maximum.reduceat
in order to get maximum values of groups that starts at indices idx
specified and display it concatenated rightwise to u
.
Remark: I used numpy
here, a widely used library that allows to push looping into C level which is much faster. Purely pythonic solutions are worth attention too.
Bonus: This is actually a one liner using a numpy_indexed
library (not so widely used) dedicated for groupby operations of arrays:
import numpy_indexed as npi
import numpy as np
np.transpose(npi.group_by(lst[:, 0]).max(lst[:, 1]))