3

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;
Theo
  • 1,385
  • 2
  • 10
  • 19

2 Answers2

5

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
Cam.Davidson.Pilon
  • 1,606
  • 1
  • 17
  • 31
1

There's also numpy.ediff1d, which allows you to explicitly prepend or append to the diff using the to_end and to_begin parameters, e.g.:

>>> import numpy as np
>>> a = np.arange(10.)
>>> diff = np.ediff1d(a,to_begin = a[:2].sum()) / 2.
>>> diff
array([ 0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5,  0.5])
>>> diff.size
10
John Vinyard
  • 12,997
  • 3
  • 30
  • 43