Zennie
Zennie

Reputation: 375

Moving window sum on a boollean array, with steps.

I'm struggling with creating a moving window sum function that calculates the number of True values in a given numpy Boolean array my_array, with a window size of n and in jumping steps of s.

For example, consider array my_array = [True, True, False, False, True, False, True]

the sum of a moving window of size n = 2 and with steps s = 2 should yield result = [2, 0, 1, 1], notice that the last window contains only one value.

I was trying my luck with itertools but to no avail.

Any help would be kindly appreciated.

Upvotes: 0

Views: 262

Answers (2)

dobkind
dobkind

Reputation: 426

Since you tagged numpy:

my_array = [True, True, False, False, True, False, True]
n = 2
s = 2
result = np.convolve(my_array, np.ones(n, ), mode='valid')[::s]

Upvotes: 2

Krishna
Krishna

Reputation: 1362

Straight forward. Following code should do.

def fun(arr, n, s):
    res = []

    for i in range(0, len(arr), s):
        res.append(sum(arr[i:i+n]))

    return res

my_array = [True, True, False, False, True, False, True]
print(fun(my_array, 2, 2))

Upvotes: 1

Related Questions