How to bin a 2D array in numpy?

Viewed 12694

I'm new to numpy and I have a 2D array of objects that I need to bin into a smaller matrix and then get a count of the number of objects in each bin to make a heatmap. I followed the answer on this thread to create the bins and do the counts for a simple array but I'm not sure how to extend it to 2 dimensions. Here's what I have so far:

data_matrix = numpy.ndarray((500,500),dtype=float)
# fill array with values.

bins = numpy.linspace(0,50,50)
digitized = numpy.digitize(data_matrix, bins)

binned_data = numpy.ndarray((50,50))
for i in range(0,len(bins)):
    for j in range(0,len(bins)):
        k = len(data_matrix[digitized == i:digitized == j]) # <-not does not work
        binned_data[i:j] = k

P.S. the [digitized == i] notation on an array will return an array of binary values. I cannot find documentation on this notation anywhere. A link would be appreciated.

3 Answers
Related