3

I have a numpy multidimensional array with sequences of zeros and ones. I want to replace the zero for any sequence 101. For example:

a = np.array([[0,0,1,0,1],[1,0,1,1,1], [1,1,1,1,1], [1,1,1,0,1]])

should become:

a = np.array([[0,0,1,1,1],[1,1,1,1,1], [1,1,1,1,1], [1,1,1,1,1]])

1 Answer 1

2

We can use 2D convolution -

from scipy.signal import convolve2d

k = np.array([[1,0,1]]) # kernel for convolution
a[(convolve2d(a,k,'same')==2) & (a==0)] = 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Using 2D convolution works for this case. Is there a way to solve this if the case changes? For example, replacing a sequence of [1,0.5, 0.5,1] with [1 0 0 1] anywhere in the ndarray.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.