繁体   English   中英

如何在没有for循环的情况下对python中的数组进行采样

[英]How to down sample an array in python without a for loop

有没有一种“ 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]

看一下这个情节:

在此处输入图片说明

您需要功能np.ix_ ,如下所示:

import numpy as np


unsampled_array = np.array([1,3,5,7,9,11,13,15,17,19])
number_of_samples = 5
downsampling_indices = np.linspace(0, len(unsampled_array)-1, number_of_samples).round()
downsampling_indices = np.array(downsampling_indices, dtype=np.int64)

indices = np.ix_(downsampling_indices)
downsampled_array = unsampled_array[indices]

print(downsampled_array)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM