python - 如何对一维 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)
解决方案
您的初始采样率 8000 不能被 6000 整除,因此不能像引用的帖子那样简单地对其进行下采样。在您的场景中,scipy 的重采样应该可以工作。
from scipy import signal
downsampled = signal.resample(y, 6000)
推荐阅读
- javascript - 如何在 Go.js 节点上设置键值以创建链接
- python-3.x - 将一个变化的变量附加到一个列表中,然后比较它们
- c++ - 在执行 new 期间是否可以在构造函数中传递不同的参数?
- c# - System.IO.Compression.GZipStream 中的 Powershell 和 Powershell Core 差异
- javascript - 如何制作函数参数
- python - 如何将字典的键转换为单列熊猫数据框?
- visual-studio-code - 如何设置 Visual Studio Code 来编译和运行 C 代码?
- ansible - Ansible 模板忽略行尾差异 LF CRLF。插件?
- c# - 使用 TopShelf 创建 Windows 服务时出现“错误 1053 服务未响应”错误
- c# - 为什么计数器在线程池中不起作用