Home > Mobile >  How to Add 5 to each element of an array and replace the old elements with the new ones (after 5)?
How to Add 5 to each element of an array and replace the old elements with the new ones (after 5)?

Time:06-07

See I wrote the code already, and this works for an array with heterogeneous elements (e.g. [2 3 4 5] (different elements), however, if the elements are homogenous (e.g. [2 5 5 8]), the output doesn't work as expected. How do I fix this?

code below:

import numpy as np

x = np.array([1, 2, 3, 3, 5])

print("arrray x is" " " str(x))

print()

i = 0

while i<(len(x)):

    z = (x[i] 5)

    print("The new value for x[" str(i) "] is" " " str(z))

    j = 0

    while j<(len(x)):

        if (x[j] 5) == z:

            x = np.where(x==x[j], z, x)

        j  = 1

    i =1

print()

print("Now the array x is" " " str(x))

CodePudding user response:

Try this one.

import numpy as np
x = np.array([1, 2, 3, 3, 5])

new_lst = x 5
print(new_lst)

OUTPUT [6, 7, 8, 8, 10]

Thanks, @matszwecja.

  • Related