Is there a quick way (so no for loops) to find the majority element per row in a numpy array and create a new array out of this?
For example, if you have the following numpy array:
X =
[[ 1. 1. 1.]
[ 1. 0. 1.]
[ 1. 0. 1.]
[ 1. 1. 1.]
[ 1. 0. 1.]
[ 1. 0. 1.]
[ 0. 0. 0.]
[ 1. 1. 1.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
you could do get_majority(X)
, which would output
[ 1. 1. 1. 1. 1. 1. 0. 1. 0. 0. 0.]
I've tried doing this by looping over the matrix and using a Counter
from collections
, but that's extremely slow for large matrices, so I want to find a vectorised way to do it.
You could use Scipy's mode -
from scipy.stats import mode
mode(X, axis=-1)[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With