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 add noise to the first index in nump array

How to add noise to the first index of array,with the number of iterations the max number iteration is 2.

I want to add a noise in range (1, max_iterator) to rows in order, for example:

  • add 0.788 to row 1st
  • add 1.233 to row 2nd
  • add 0.788 to row 3rd
  • add 1.233 to row 4th
  • and 0.788 to row 5th
  • and so on

I’ve tried to use this code but it doesn’t work

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

a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]])
noise = np.random.normal(loc=0, scale=0.1, size=1)
max_iter = 2
for i in range(max_iter):
    for j in range(len(a)):
        a[i][0] = np.clip(a[i][0] + noise, a_min=0.0, a_max=None)
print(a)

>Solution :

You can do:

# you'll need to cast the array as floats rather ints to add other floats
a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]]).astype(float)

n = 2

# create n random values
noise = np.random.normal(loc=0, scale=0.1, size=n)

# loop through rows in steps of n
for i in range(0, a.shape[0], n):
    a[i:i + n, 0] = np.clip(a[i:i + 1, 0] + noise, a_min=0.0, a_max=None)
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