【问题标题】:How to down sample an array in python without a for loop如何在没有for循环的情况下在python中对数组进行下采样
【发布时间】:2019-02-25 02:17:01
【问题描述】:

是否有一种 '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]

【问题讨论】:

    标签: python arrays numpy downsampling


    【解决方案1】:

    如果你想要“真正的”下采样,其中每个值是 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]
    

    看看这个情节:

    【讨论】:

    • 你是对的。我没有在问题中提到它,但我最初对对象的下采样以及样本大小之间的下采样感兴趣。我想我过度简化了这个例子。
    【解决方案2】:

    你需要函数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)
    

    【讨论】:

    • 我认为np.ix_ 根本没有必要。你可以去unsampled_array[ downsampling_indices]
    • 这很棒,因为它也适用于非整数下采样(即 10->7)
    • np.ix_ 非常快。您可以比较这两种方法。
    • 不要使用 dtype=np.int64 调用 np.array,而是将 astype(int) 添加到 np.linspace 命令的末尾。另外,我不会使用圆形,而是使用 np.rint。
    • @NoamPeled 您对astype(int) 的看法是正确的,但np.rint 出于某种原因返回了一个浮点数,因此np.rint(x).astype(int)x.round().astype(int) 相比没有任何好处
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多