对一维 numpy 数组进行下采样 [英] Downsample a 1D numpy array
问题描述
我有一个一维 numpy 数组,我想对其进行下采样.如果下采样栅格与数据不完全吻合,以下任何一种方法都可以接受:
I have a 1-d numpy array which I would like to downsample. Any of the following methods are acceptable if the downsampling raster doesn't perfectly fit the data:
- 重叠下采样间隔
- 将末尾剩余的任意数量的值转换为单独的下采样值
- 插值以适应光栅
基本上如果我有
1 2 6 2 1
我将采样率降低了 3 倍,以下所有情况都可以:
and I am downsampling by a factor of 3, all of the following are ok:
3 3
3 1.5
或者任何插值会给我这里.
or whatever an interpolation would give me here.
我只是在寻找最快/最简单的方法来做到这一点.
I'm just looking for the fastest/easiest way to do this.
我找到了 scipy.signal.decimate
,但这听起来像是抽取值(根据需要将它们取出并只在 X 中留下一个).scipy.signal.resample
似乎有正确的名称,但我不明白他们在描述中的整个傅立叶事物的去向.我的信号不是特别周期性.
I found scipy.signal.decimate
, but that sounds like it decimates the values (takes them out as needed and only leaves one in X). scipy.signal.resample
seems to have the right name, but I do not understand where they are going with the whole fourier thing in the description. My signal is not particularly periodic.
你能帮我一把吗?这似乎是一项非常简单的任务,但所有这些功能都非常复杂......
Could you give me a hand here? This seems like a really simple task to do, but all these functions are quite intricate...
推荐答案
在数组大小可以被下采样因子 (R
) 整除的简单情况下,您可以重塑
代码>您的数组,并沿新轴取平均值:
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])
在一般情况下,您可以使用 NaN
将数组填充到可被 R
整除的大小,并使用 scipy.nanmean取平均值代码>.
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.])
这篇关于对一维 numpy 数组进行下采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!