Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

IDL rebin in python

View rebin.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
import numpy as np
 
def rebin(a, new_shape):
"""
Resizes a 2d array by averaging or repeating elements,
new dimensions must be integral factors of original dimensions
Parameters
----------
a : array_like
Input array.
new_shape : tuple of int
Shape of the output array
Returns
-------
rebinned_array : ndarray
If the new shape is smaller of the input array, the data are averaged,
if the new shape is bigger array elements are repeated
See Also
--------
resize : Return a new array with the specified shape.
Examples
--------
>>> a = np.array([[0, 1], [2, 3]])
>>> b = rebin(a, (4, 6)) #upsize
>>> b
array([[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[2, 2, 2, 3, 3, 3],
[2, 2, 2, 3, 3, 3]])
>>> c = rebin(b, (2, 3)) #downsize
>>> c
array([[ 0. , 0.5, 1. ],
[ 2. , 2.5, 3. ]])
"""
M, N = a.shape
m, n = new_shape
if m<M:
return a.reshape((m,M/m,n,N/n)).mean(3).mean(1)
else:
return np.repeat(np.repeat(a, m/M, axis=0), n/N, axis=1)
 
if __name__ == '__main__':
import doctest
doctest.testmod()

Came across your method from stackoverflow and wanted to let you know it only works for regular numpy arrays. This method produces wrong results for masked arrays.
-marius

Hey I have written a version of this function for ndarrays with arbitrary dimensions:
https://gist.github.com/derricw/95eab740e1b08b78c03f
It also lets you sum or average.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.