Home > database >  How do I do an elementwise sum of the current element and next three row elements (in column 0) usin
How do I do an elementwise sum of the current element and next three row elements (in column 0) usin

Time:07-16

I am trying to do an operation relative to the location of the element during an elementwise numpy operation. I cannot figure out how access the current location in order to sum it with the next three elements. I have included a sample array as well as a sample solution I am trying to achieve. Since the real array is over 1MM rows a for loop would be too slow. Thank you!

import numpy as np

k = np.random.rand(10,1)*10
k.astype(int)

sample goal solution

CodePudding user response:

Try np.convolve:

N = 3
x = np.convolve(k.ravel(), np.ones(N, dtype=int), "full")[N - 1 :].reshape(-1, 1)
print(x)

Prints:

[[17]
 [14]
 [ 5]
 [14]
 [14]
 [15]
 [11]
 [14]
 [13]
 [ 8]]

The input array was:

[[8]
 [9]
 [0]
 [5]
 [0]
 [9]
 [5]
 [1]
 [5]
 [8]]
  • Related