user1220022
user1220022

Reputation: 12075

Numpy bincount() with floats

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?

Upvotes: 11

Views: 14982

Answers (3)

CK1
CK1

Reputation: 714

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)

Upvotes: 11

Bi Rico
Bi Rico

Reputation: 25813

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])

Upvotes: 14

eumiro
eumiro

Reputation: 212835

You want something like this?

>>> from collections import Counter
>>> w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
>>> c = Counter(w)

Counter({0.10000000000000001: 2, 0.5: 1, 0.29999999999999999: 1, 0.20000000000000001: 1})

or, more nicely output:

Counter({0.1: 2, 0.5: 1, 0.3: 1, 0.2: 1})

You can then sort it and get your values:

>>> np.array([v for k,v in sorted(c.iteritems())])

array([2, 1, 1, 1])

The output of bincount wouldn't make sense with floats:

>>> np.bincount([10,11])
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1])

as there is no defined sequence of floats.

Upvotes: 6

Related Questions