Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: for loop compact representation

Tags:

python

numpy

Python, Numpy

Is there a more compact way to operate on array elements, without having to use the standard for loop.?

For example, consider the function below:

filterData(A):
    B = numpy.zeros(len(A));
    B[0] = (A[0] + A[1])/2.0;
    for i in range(1, len(A)): 
        B[i] = (A[i]-A[i-1])/2.0;
    return B;
like image 232
Theo Avatar asked Sep 25 '26 00:09

Theo


1 Answers

Numpy has a diff operator that works on both numpy arrays and Python native arrays. You can rewrite your code as:

def filterData(A):
    B = numpy.zeros(len(A));
    B[1:] = np.diff( A )/2.0
    B[0] = (A[0] + A[1])/2.0;
    return B
like image 119
Cam.Davidson.Pilon Avatar answered Sep 27 '26 12:09

Cam.Davidson.Pilon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!