下采样一维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
,但这听起来像是 decimates 值(根据需要将其取出,只在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
)整除,则可以reshape
数组,并取平均值新轴:
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屋!