Reduce resolution of array through summation
numpy, python
Solution
With your example:
a.reshape(2,2,2,2).sum(axis=1).sum(axis=2)
returns:
array([[14, 22],
[46, 54]])
Now let's create a general function…
def shrink(data, rows, cols):
return data.reshape(rows, data.shape[0]/rows, cols, data.shape[1]/cols).sum(axis=1).sum(axis=2)
works for your examples:
In [19]: shrink(a, 2,2)
Out[19]:
array([[14, 22],
[46, 54]])
In [20]: shrink(a, 2,1)
Out[20]:
array([[ 36],
[100]])
Problem
If I have an array like this: ``` a = np.array([[ 1, 2, 3, 4], [ 5 ,6, 7, 8], [ 9,10,11,12], [13,14,15,16]]) ``` I want to 'change the resolution', and end up with a smaller array, (say 2 rows by 2 cols, or 2 rows by 4 cols, etc.). I want this resolution change to happen through summation. I need this to work with large arrays, the number of rows, cols of the smaller array will always be a factor of the larger array. Reducing the above array to a 2 by 2 array would result in (which is what I want): ``` [[ 14. 22.] [ 46. 54.]] ``` I have this function that does it fine: ``` import numpy as np def shrink(data, rows, cols): shrunk = np.zeros((rows,cols)) for i in xrange(0,rows): for j in xrange(0,cols): row_sp = data.shape[0]/rows col_sp = data.shape[1]/cols zz = data[i*row_sp : i*row_sp + row_sp, j*col_sp : j*col_sp + col_sp] shrunk[i,j] = np.sum(zz) return shrunk print shrink(a,2,2) print shrink(a,2,1) #correct output: [[ 14. 22.] [ 46. 54.]] [[ 36.] [ 100.]] ``` I've had a long look through the examples, but can't seem to find anything that helps. Is there a faster way to do this, without needing the loops?