How to organize values โ€‹โ€‹in a numpy array into cells containing a certain range of values?

I am trying to sort the values โ€‹โ€‹in a numpy array so that I can store all the values โ€‹โ€‹that are in a certain range (this can probably be formulated better). In any case, I am not showing a good example of what I'm trying to do. I have an array called cells that looks like this:

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

I also have another array called 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'm trying to do is find the index values โ€‹โ€‹of the avgs array, which are in the ranges between the values โ€‹โ€‹of the bins array. For example, I tried to create a while loop that would create new variables for each bean. The first bunker will be everything between bins[0] and bins[1] and will look like this:

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

These index values โ€‹โ€‹will correspond to values โ€‹โ€‹11.02, 11.3 and 11.01 in avgs and there will be avgs values โ€‹โ€‹that were between index values โ€‹โ€‹0 and 1 in bins . I also need other bins, so another example:

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

However, the difficult part for me was that the size of bins and avgs changes depending on other parameters, so I tried to create something that could be expanded to larger or smaller bins and avgs arrays.

+7
python arrays numpy
source share
1 answer

Numpy has some pretty powerful bin counting functions.

 >>> 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]) 
+9
source share

All Articles