1

Possible Duplicate:
Grouping 2D numpy array in average

I need to 'down-sample' a 2d array of shape (2880, 5760) to shape (360, 720) by averageing over blocks of 8x8 elements of the original array. Which would be an efficient way of doing that using NumPy?

EDIT I just realize I need to do this on masked_arrays, so the chained mean() won't do.

Community
  • 1
  • 1
andreas-h
  • 10,679
  • 18
  • 60
  • 78

2 Answers2

0

First introduce two extra axes, then take the means along those axes. If X is your data:

X.reshape(360, 8, 720, 8).mean(axis=3).mean(axis=1)
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

Here is the way which works for masked arrays as well

import numpy as np, numpy.random
nx = 100
ny = 101
bx = 3
by = 4
arr = np.random.uniform(size = (nx * bx, ny * by))
arr = np.ma.masked_array(arr,arr<.1)
rebinarr = np.swapaxes(arr.reshape(nx, bx, ny, by), 1, 2).reshape(nx, ny, bx * by).mean(axis=2)
print rebinarr.shape
>> (100,101)
sega_sai
  • 8,328
  • 1
  • 29
  • 38