0

I have a 2D numarray, of size WIDTHxHEIGHT. I would like to bin the array by finding the median of each bin so that the resultant array is WIDTH/binsize x HEIGHT/binsize. Assume that both WIDTH and HEIGHT are divisible by binsize. Edit: An example is given in the attached image.

I have found solutions where the binned array values are the sum or average of the individual elements in each bin: How to bin a 2D array in numpy?

However, if I want to do a median combine of elements in each bin, I haven't been able to figure out a solution. Your help would be much appreciated!

Edit: image added An example of the initial array and desired resultant median binned array

Community
  • 1
  • 1
user3835290
  • 136
  • 1
  • 7

1 Answers1

1

So you are looking for median over strided reshape:

import numpy as np
a = np.arange(24).reshape(4,6)

def median_binner(a,bin_x,bin_y):
    m,n = np.shape(a)
    strided_reshape = np.lib.stride_tricks.as_strided(a,shape=(bin_x,bin_y,m//bin_x,n//bin_y),strides = a.itemsize*np.array([(m / bin_x) * n, (n / bin_y), n, 1]))
    return np.array([np.median(col) for row in strided_reshape for col in row]).reshape(bin_x,bin_y)



print "Original Matrix:"
print a
print "\n"
bin_tester1 = median_binner(a,2,3)
print "2x3 median bin :"
print bin_tester1
print "\n"
bin_tester2 = median_binner(a,2,2)
print "2x2 median bin :"
print bin_tester2

result:

Original Matrix:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]


2x3 median bin :
[[  3.5   5.5   7.5]
 [ 15.5  17.5  19.5]]


2x2 median bin :
[[  4.   7.]
 [ 16.  19.]]

Read this in order to completely understand the following line in the code:

strided_reshape = np.lib.stride_tricks.as_strided(a,shape=(bin_x,bin_y,m//bin_x,n//bin_y),strides = a.itemsize*np.array([(m / bin_x) * n, (n / bin_y), n, 1])) .

Kennet Celeste
  • 4,175
  • 2
  • 21
  • 32
  • Thanks! This isn't quite what I was looking for, I made a diagram to make it more clear in my question above. – user3835290 Oct 21 '16 at 21:35
  • Here you have median binned 0,1,2,3 then 4,5,6,7 then 8,9,10,11 etc. I want to bin 0,1,6,7 then 2,3,8,9 then 4,5,10,11 etc. – user3835290 Oct 21 '16 at 21:38
  • @user3835290 I know understood your problem and fixed the code based on what you asked. Please "accept" the answer like [here](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) so that other people can see find it as well. – Kennet Celeste Oct 22 '16 at 22:03