0

I have an array A of n elements. I want to create a window of some fixed size(e.g 5000) that would take the first 5000 elements of the array A then perform an operation of recording the sum of squared elements of input falling within the windows and print this sum or store this sum in another array.

and repeat the same for the next 5000 elements and so on until I reach the nth element by using a loop(e.g for).

in Python using numpy or scipy?

Nish
  • 183
  • 7

1 Answers1

1

If the windows are non-overlapping, you should be able to use reshape:

>>> A=np.arange(10000)

>>> A
array([   0,    1,    2, ..., 9997, 9998, 9999])

# pad A to be a multiple of 2205
>>> Ap = np.pad(A, (0,int(np.ceil(len(A) / 2205.)) * 2205 - len(A)),
                'constant', constant_values=0)

# reshape A
>>> Apr = Ap.reshape((len(Ap) // 2205, 2205))

>>> Apr.shape
(5, 2205)

# perform the windowing function along axis 1
# sum of squares
>>> (Apr ** 2).sum(axis=1)
array([  3571157730,  25007825955,  67886024430, 132205753155, 104612573730])

If you mean that you want to take sets of 2205 elements, each one starting one element offset from the previous, this is sometimes referred to as a rolling window:

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

>>> rolling_window(np.arange(10), 5)
array([[0, 1, 2, 3, 4],
       [1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8],
       [5, 6, 7, 8, 9]])

# sum of squares
>>> (rolling_window(np.arange(10), 5) ** 2).sum(axis=1)
array([ 30,  55,  90, 135, 190, 255])
Community
  • 1
  • 1
wildwilhelm
  • 4,809
  • 1
  • 19
  • 24
  • Hey! after getting the array of the sum of squares i am removing the set of elements that are falling below a particular threshold by using the filter function and storing the remaining elements in a separate array lets say "B" ! Now I require the starting and the ending index of the windows of the elements in B! I hope I am clear with my doubt! Thanks a lot for the help though! – Nish Nov 23 '16 at 14:27
  • `I got the starting index using np.where() function..how to find the ending index of the window?and then I want to take out all the elements which fall under that window i.e: within the starting and ending index – Nish Nov 23 '16 at 17:29