Skip to content Skip to sidebar Skip to footer

How To Sample A Numpy Array And Perform Computation On Each Sample Efficiently?

Assume I have a 1d array, what I want is to sample with a moving window and within the window divide each element by the first element. For example if I have [2, 5, 8, 9, 6] and a

Solution 1:

Here's a vectorized approach using broadcasting -

N = 3# Window sizenrows = a.size-N+1a2D = a[np.arange(nrows)[:,None] + np.arange(N)]
out = a2D/a[:nrows,None].astype(float)

We can also use NumPy strides for a more efficient extraction of sliding windows, like so -

n = a.strides[0]
a2D = np.lib.stride_tricks.as_strided(a,shape=(nrows,N),strides=(n,n))

Sample run -

In [73]: a
Out[73]: array([4, 9, 3, 6, 5, 7, 2])

In [74]: N =3
    ...: nrows = a.size-N+1
    ...: a2D = a[np.arange(nrows)[:,None] + np.arange(N)]
    ...: out= a2D/a[:nrows,None].astype(float)
    ...: 

In [75]: outOut[75]: 
array([[ 1.        ,  2.25      ,  0.75      ],
       [ 1.        ,  0.33333333,  0.66666667],
       [ 1.        ,  2.        ,  1.66666667],
       [ 1.        ,  0.83333333,  1.16666667],
       [ 1.        ,  1.4       ,  0.4       ]])

Post a Comment for "How To Sample A Numpy Array And Perform Computation On Each Sample Efficiently?"