python - 如何在不使用for循环的情况下对python中的数组进行下采样

标签 python arrays numpy downsampling

有没有一种'pythonic'方法可以在不使用多个for循环的情况下干净地进行下采样?

下面的示例是我希望摆脱的 for 循环类型。

最小工作示例:

import numpy as np
unsampled_array = [1,3,5,7,9,11,13,15,17,19]
number_of_samples = 7
downsampled_array = []
downsampling_indices = np.linspace(0, len(unsampled_array)-1, number_of_samples).round()
for index in downsampling_indices:
    downsampled_array.append(unsampled_array[int(index)])
print(downsampled_array)

结果:

>>> [ 1  5  7  9 13 17 19]

最佳答案

如果您想要“真正的”下采样,其中每个值都是 k 值的平均值,您可以使用

unsampled_array.reshape(-1, k).mean(1) 

确保 unsampled_array 是 np.array。在你的情况下,k=2。这会给你:

[ 2. 6. 10. 14. 18.]

*更新:如果您只想获取每 k 个项目的第一个项目,您可以使用以下代码:

unsampled_array.reshape(-1, 2)[:, 0]

看看这个图:

enter image description here

关于python - 如何在不使用for循环的情况下对python中的数组进行下采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858623/

相关文章:

python - 为什么 np.array 将列表及其元素转换为数组?

python - 在 python 中更快地实现 ReLu 导数?

c - C中未知矩阵的动力学分配

JavaScript:无法从函数正确返回数组

python - 为什么在只有一个线程的情况下需要使用线程锁? (Python)

python - 从 lm_sensors 命令解析温度

具有无法预定义的替代长度的 Python (NumPy) 数组

python - Pandas 在 groupby 中按条件过滤

python - 实现 group_by_owners 字典

javascript - Django - 在 for 循环中每隔一个项目放置不同的位置