rougier/numpy-100

Q.83 - `np.bincount` doesn't work on negative values

iamyifan opened this issue · 2 comments

Hi @rougier,

Q.83 asks How to find the most frequent value in an array?
And the current answer is:

Z = np.random.randint(0,10,50)
print(np.bincount(Z).argmax())

The document says np.bincount can only count nonnegative ints in 1-dimension arrays, which is not universal and not helpful in some scenarios.

A possible solution will be:

Z = np.random.randint(0, 10, 50)
# returns the sorted unique elements and their corresponding counts
uniq_vals, counts = np.unique(Z, return_counts=True)
most_freq_val = uniq_vals[counts.argmax()]
print(most_freq_val)

Cheers,
@iamyifan

Thanks. For generic case, you can use np.bincount(Z-Z.min()).argmax()