# [Numpy-discussion] 2d binning on regular grid

josef.pktd@gmai... josef.pktd@gmai...
Thu Jun 3 16:11:34 CDT 2010

```On Wed, Jun 2, 2010 at 11:40 AM, Andreas Hilboll <lists@hilboll.de> wrote:
> Hi there,
>
> I'm interested in the solution to a special case of the parallel thread
> '2D binning', which is going on at the moment. My data is on a fine global
> grid, say .125x.125 degrees. I'm looking for a way to do calculations on
> coarser grids, e.g.
>
> * calculate means()
> * calculate std()
> * ...
>
> on a, say, 2.5x3.75 degree grid. One very crude approach would be to
> iterate through latitudes and longitudes, like this:
>
>
> latstep_orig = .125
> lonstep_orig = .125
> data_orig =
> np.arange((180./latstep_orig)*(360./lonstep_orig)).reshape((180./latstep_orig,360./lonstep_orig))
> latstep_new = 2.5
> lonstep_new = 3.75
> latstep = int(latstep_new / latstep_orig)
> lonstep = int(lonstep_new / lonstep_orig)
>
> print 'one new lat equals',latstep,'new lats'
> print 'one new lon equals',lonstep,'new lons'
>
> result = ma.zeros((180./latstep_new,360./lonstep_new))
> latidx = 0
> while latidx*latstep_new < 180.:
>    lonidx = 0
>    while lonidx*lonstep_new < 360.:
>        m = np.mean( \
>            data_orig[latidx*latstep:(latidx+1)*latstep, \
>            lonidx*lonstep:(lonidx+1)*lonstep])
>        result[latidx,lonidx] = m
>        lonidx += 1
>    latidx += 1
>
> However, this is very crude, and I was wondering if there's any more
> elegant way to do it ...
>

I thought maybe there is something in ndimage for this, but since
nobody mentions it, maybe not.

If there are no memory problems and my interpretation of the question
is correct, then something like this might work:

>>> x = np.arange(16).reshape(4,-1)
>>> d = np.kron(np.eye(2),np.ones(2))
>>> s = np.dot(np.dot(d,x),d.T)
>>> m = np.dot(np.dot(d,x),d.T)/4
>>> v = np.dot(np.dot(d,x**2),d.T)/4 - m**2
>>> x
array([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11],
[12, 13, 14, 15]])
>>> s
array([[ 10.,  18.],
[ 42.,  50.]])
>>> m
array([[  2.5,   4.5],
[ 10.5,  12.5]])
>>> v
array([[ 4.25,  4.25],
[ 4.25,  4.25]])
>>> x[:2,:2].sum()
10
>>> x[:2,:2].mean()
2.5
>>> x[:2,:2].var()
4.25

Josef

> A.
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
```