首页 > 解决方案 > 如何对一维 numpy 数组进行下采样?

问题描述

这似乎是一个非常直接的问题,但我无法找到解决方案。假设我有一个y包含 8000 个样本的正弦函数:

import numpy as np

Fs = 8000
f = 1
npts = 8000
x = np.arange(npts)
y = np.sin(2 * np.pi * f * x / Fs)

我想将此函数下采样到 6000 个样本,所以我尝试了类似问题的这个答案的方法......

import math
from scipy import nanmean

#number of samples I want to downsample to
npts2 = 6000

#calculating the number of NaN values to pad to the array
n = math.ceil(float(y.size)/npts2)
pad_size = n*npts2 - len(y)
padded = np.append(y, np.zeros(int(pad_size))*np.NaN)

#downsampling the reshaped padded array with nanmean
downsampled = nanmean(padded.reshape((npts2, int(n))), axis = 1)

这给了我一个正确长度的数组(6000),但最后 2000 个样本(即原始npts和之间的差异npts2)是NaN,并且函数本身只占用前 4000 个样本。

有没有更好的方法可以使这个正弦函数长度为 6000 个样本?谢谢!

编辑

感谢您的回复 - 我现在意识到我以错误的方式攻击这个。我决定在该scipy.interpolate.interp1d函数上使用该y函数,然后将一个数组传递给它,该np.linspace数组使用所需的点数生成以进行插值。这给了我正确缩放的输出。

from scipy.interpolate import interp1d

def downsample(array, npts):
    interpolated = interp1d(np.arange(len(array)), array, axis = 0, fill_value = 'extrapolate')
    downsampled = interpolated(np.linspace(0, len(array), npts))
    return downsampled

downsampled_y = downsample(y, 6000)

标签: pythonnumpydownsampling

解决方案


您的初始采样率 8000 不能被 6000 整除,因此不能像引用的帖子那样简单地对其进行下采样。在您的场景中,scipy 的重采样应该可以工作。

from scipy import signal
downsampled =  signal.resample(y, 6000)

推荐阅读