如何将numpy数组中的值组织成包含特定值范围的bin?

时间:2021-04-15 21:34:49

I am trying to sort values in an numpy array so that I can store all of the values that are in a certain range (That could probably be phrased better). Anyway ill give an example of what I am trying to do. I have an array called bins that looks like this:

我试图在一个numpy数组中排序值,以便我可以存储在一定范围内的所有值(这可能是更好的措辞)。无论如何生病了我想要做的一个例子。我有一个名为bin的数组,如下所示:

bins = array([11,11.5,12,12.5,13,13.5,14])

I also have another array called avgs:

我还有另一个名为avgs的数组:

avgs = array([11.02, 13.67, 11.78, 12.34, 13.24, 12.98, 11.3, 12.56, 13.95, 13.56,
              11.64, 12.45, 13.23, 13.64, 12.46, 11.01, 11.87, 12.34, 13,87, 13.04,
              12.49, 12.5])

What I am trying to do is to find the index values of the avgs array that are in the ranges between the values of the bins array. For example I was trying to make a while loop that would create new variables for each bin. The first bin would be everything that is between bins[0] and bins[1] and would look like:

我想要做的是找到avgs数组的索引值,这些索引值在bin数组的值之间的范围内。例如,我试图创建一个while循环,为每个bin创建新的变量。第一个bin将是bin [0]和bin [1]之间的所有内容,看起来像:

bin1 = array([0, 6, 15])

Those index values would correspond to the values 11.02, 11.3, and 11.01 in the avgs and would be the values of avgs that were between index values 0 and 1 in bins. I also need the other bins so another example would be:

那些索引值将对应于avgs中的值11.02,11.3和11.01,并且将是在箱中的索引值0和1之间的avgs的值。我还需要其他箱子,所以另一个例子是:

bin2 = array([2, 10, 16])

However the challenging part of this for me was that the size of bins and avgs changes based on other parameters so I was trying to build something that would be able to be expanded to larger or smaller bins and avgs arrays.

然而,这对我来说具有挑战性的部分是,bin和avgs的大小根据其他参数而变化,所以我试图构建一些能够扩展到更大或更小的bin和avgs数组的东西。

1 个解决方案

#1


9  

Numpy has some pretty powerful bin counting functions.

Numpy有一些非常强大的bin计数功能。

>>> binplace = np.digitize(avgs, bins) #Returns which bin an average belongs
>>> binplace
array([1, 6, 2, 3, 5, 4, 1, 4, 6, 6, 2, 3, 5, 6, 3, 1, 2, 3, 5, 7, 5, 3, 4])

>>> np.where(binplace == 1)
(array([ 0,  6, 15]),)
>>> np.where(binplace == 2)
(array([ 2, 10, 16]),)

>>> avgs[np.where(binplace == 1)]
array([ 11.02,  11.3 ,  11.01])

#1


9  

Numpy has some pretty powerful bin counting functions.

Numpy有一些非常强大的bin计数功能。

>>> binplace = np.digitize(avgs, bins) #Returns which bin an average belongs
>>> binplace
array([1, 6, 2, 3, 5, 4, 1, 4, 6, 6, 2, 3, 5, 6, 3, 1, 2, 3, 5, 7, 5, 3, 4])

>>> np.where(binplace == 1)
(array([ 0,  6, 15]),)
>>> np.where(binplace == 2)
(array([ 2, 10, 16]),)

>>> avgs[np.where(binplace == 1)]
array([ 11.02,  11.3 ,  11.01])