Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy bincount() with floats

Tags:

python

numpy

I am trying to get a bincount of a numpy array which is of the float type:

w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
print np.bincount(w)

How can you use bincount() with float values and not int?

like image 286
user1220022 Avatar asked Apr 12 '12 07:04

user1220022


People also ask

How does bincount work NumPy?

Count number of occurrences of each value in array of non-negative ints. The number of bins (of size 1) is one larger than the largest value in x. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of x).

What does bincount do?

bincount returns the count of values in each bin from 0 to the largest value in the array i.e.


2 Answers

You need to use numpy.unique before you use bincount. Otherwise it's ambiguous what you're counting. unique should be much faster than Counter for numpy arrays.

>>> w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
>>> uniqw, inverse = np.unique(w, return_inverse=True)
>>> uniqw
array([ 0.1,  0.2,  0.3,  0.5])
>>> np.bincount(inverse)
array([2, 1, 1, 1])
like image 138
Bi Rico Avatar answered Oct 25 '22 04:10

Bi Rico


Since version 1.9.0, you can use np.unique directly:

w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
values, counts = np.unique(w, return_counts=True)
like image 21
CK1 Avatar answered Oct 25 '22 04:10

CK1