Nishranth Saravanan - 7 months ago 38

Python Question

I have an array A of n elements.

I want to create a window of some fixed size(e.g 2205) that would take the first 2205 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 2205 elements and so on until I reach the nth element by using a loop(e.g for).

in Python using numpy or scipy?

Answer

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])
```

Source (Stackoverflow)