Reputation: 3828
Wondering if there is an easy function in numpy to get counts of values within a ranges. For example
import numpy as np
rand_vals = np.random.rand(10)
#Out > arrayarray([[0.15068161, 0.51291888, 0.99576726, 0.05944532, 0.72641707,
0.09693093, 0.61988549, 0.19811334, 0.88184011, 0.16775108]])
bins = np.linspace(0,1,11)
#Out> array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
#Expected Out > [2, 3, 0, 0, 0, 1, 1, 1, 1, 1]
#The first entry is 2 since there are two values between 0 to 0.1 (0.0584432, 0.09693093)
#The second entry is 3 since there are 3 values between 0.1 to 0.2 (0.15068161, 0.1981134, 0.16775108)
#So on ..
Upvotes: 2
Views: 307
Reputation: 2167
You can use numpy.histogram():
import numpy as np
bincount, bins = np.histogram(rand_vals, bins=np.linspace(0,1,11))
print(bincount) # => [0 2 1 0 2 0 1 1 2 1]
print(bins) # => [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
Upvotes: 4