Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading