创建 numpy 数组的缩减长度重采样

问题描述 投票:0回答:1

我有一个一定长度的 numpy 数组,并且想要生成一个更短的数组,其中较短数组中的每个值都是根据原始数组中的值的 bin 聚合的。在我的具体情况下,这恰好是一个音频信号,我应用的函数是每个 bin 的最大值。

感觉必须有一个像 numpy.interp 或 scipy.interpolate.interp1d 这样的函数可以让这变得更容易。我发誓一定有一种更简单/更干净的方法来使用 numpy 或 scipy 内置来做到这一点。

这是我现在写的代码:

# assume a is an np.array with len(a) == 510
shorten_length = 50
a_shortened = np.zeros(len(a) // shorten_length)

for i in range(len(a_shortened)):
    slice_end = min(len(a), (i+1) * shorten_length) - 1
    _bin_max = np.max(a[i * shorten_length:slice_end+1])
    a_shortened[i] = _bin_max
numpy scipy numpy-slicing
1个回答
0
投票

只要你放下最后一片(当它小于

shorten_length
时), 你可以使用这种方法:

valid_length = len(a) - len(a) % shorten_length
a_shortened = a[:valid_length].reshape(-1, shorten_length).max(axis=1)

切片或整形过程中不涉及数组复制。

© www.soinside.com 2019 - 2024. All rights reserved.