获取浮点值的bincount

2024-04-24 22:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

想知道numpy中是否有一个简单的函数可以获取范围内的值计数。比如说

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 ..

Tags: theto函数numpyisnpbetweenout
1条回答
网友
1楼 · 发布于 2024-04-24 22:23:51

您可以使用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. ]

相关问题 更多 >