Home > Software design >  Numpy BinCount for Float Values
Numpy BinCount for Float Values

Time:07-28

I am using numpy.bincount previously for integers and it worked. However, after reviewing the documentation, this method only works for integers. How can produce a similar count but for float values (between 0 and 1)?

Current Code:

import numpy as np

np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))

>>> array([1, 3, 1, 1, 0, 0, 0, 1])

np.bincount(np.array([0.91, 0.74, 1.0, 0.89, 0.91, 0.74]))

TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'

CodePudding user response:

Use np.histogram

arr = np.array([0.91, 0.74, 1.0, 0.89, 0.91, 0.74])
counts, edges = np.histogram(arr, bins=5)

print(counts)
# array([2, 0, 1, 2, 1], dtype=int64)

print(edges)
# array([0.74 , 0.792, 0.844, 0.896, 0.948, 1.   ])
  • Related