How to replace every third 0 in the numpy array consists of 0 and 1?

Question:

I’m new to Python and Stackoverflow, so I’m sorry in advance if this question is silly and/or duplicated.

I’m trying to write a code that replaces every nth 0 in the numpy array that consists of 0 and 1.

For example, if I want to replace every third 0 with 0.5, the expected result is:
Input: np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1])
Output: np.array([0, 0, 0.5, 0, 1, 1, 1, 1, 1, 0, 0.5, 1, 0, 1])

And I wrote the following code.

import numpy as np

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

counter = 0
for i in range(len(arr)):
    if arr[i] == 0 and counter%3 == 0:
        arr[i] = 0.5
    counter += 1

print(arr)

The expected output is [0, 0, 0.5, 0, 1, 1, 1, 1, 1, 0, 0.5, 1, 0, 1].

However, the output is exactly the same as input and it’s not replacing any values…
Does anyone know why this does not replace value and how I can solve this?
Thank you.

Asked By: Hit

||

Answers:

Reasonably quick and dirty:

  1. Find the indices of entries that are zero
indices = np.flatnonzero(arr == 0)
  1. Take every third of those indices
indices = indices[::3]
  1. As noted in a comment, you need a float type
arr = arr.astype(float)
  1. Set those indices to 0.5
arr[indices] = 0.5
Answered By: Homer512
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.