2

Example:

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

Goal:

Set value to 0 if the previous value is 0

Desired output:

[1, 0, 0, 0, 0, 4]

1 Answer 1

2

Make a mask of the locations that are zero:

m = (a == 0)

Apply the mask to a shifted slice of the array:

a[1:][m[:-1]] = 0

In some cases, you may want to shift by incrementing the indices:

i = np.flatnonzero(m[:-1]) + 1
a[i] = 0
Sign up to request clarification or add additional context in comments.

Comments

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.