Search code examples
pythonarraysnumpydownsampling

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


Is there a 'pythonic' way to cleanly down-sample without multiple for loops?

This example below is the type of for loop I wish to get rid of.

Minimum working example:

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)

Result:

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

Solution

  • You need function np.ix_, as follows:

    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)