In the simple case where your array's size is divisible by the downsampling factor (R
), you can reshape
your array, and take the mean along the new axis:
import numpy as np
a = np.array([1.,2,6,2,1,7])
R = 3
a.reshape(-1, R)
=> array([[ 1., 2., 6.],
[ 2., 1., 7.]])
a.reshape(-1, R).mean(axis=1)
=> array([ 3. , 3.33333333])
In the general case, you can pad your array with NaN
s to a size divisible by R
, and take the mean using scipy.nanmean
.
import math, scipy
b = np.append(a, [ 4 ])
b.shape
=> (7,)
pad_size = math.ceil(float(b.size)/R)*R - b.size
b_padded = np.append(b, np.zeros(pad_size)*np.NaN)
b_padded.shape
=> (9,)
scipy.nanmean(b_padded.reshape(-1,R), axis=1)
=> array([ 3. , 3.33333333, 4.])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…