1

I'm looking for creating a random dimension numpy array, iterate and replace values per 10 for example.

I tried :

# Import numpy library
import numpy as np

def Iter_Replace(x):
    print(x)
    for i in range(x):
        x[i] = 10
    print(x)
    

def main():
    x = np.array(([1,2,2], [1,4,3]))
    Iter_Replace(x)

main()

But I'm getting this error :

TypeError: only integer scalar arrays can be converted to a scalar index
2
  • range(x) does not make sense if x is array. What were you trying to do? Commented Mar 12, 2021 at 15:55
  • hello @hpaulj. Cyttorak understood my question. In fact I wanted to replace per 10 all the values of the arrays in the array. Commented Mar 12, 2021 at 16:02

2 Answers 2

1

There is a numpy function for this, numpy.full or numpy.full_like:

>>> x = np.array(([1,2,2], [1,4,3]))
>>> np.full(x.shape, 10)

array([[10, 10, 10],
       [10, 10, 10]])
# OR,
>>> np.full_like(x, 10)

array([[10, 10, 10],
       [10, 10, 10]])

If you want to iterate you can either use itertools.product:

>>> from itertools import product

>>> def Iter_Replace(x):
        indices = product(*map(range, x.shape))
        for index in indices:
            x[tuple(index)] = 10
        return x
>>> x = np.array([[1,2,2], [1,4,3]])
>>> Iter_Replace(x)

array([[10, 10, 10],
       [10, 10, 10]])

Or, use np.nditer

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

>>> for index in np.ndindex(x.shape):
        x[index] = 10
    
>>> x

array([[10, 10, 10],
       [10, 10, 10]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate, you got my question but the print returned : [[1 2 2] [1 4 3]]
You need to assign it back to x and then print. x = np.full_like(x, 10), print(x)
0

You have two errors. There are missing parenthesis in the first line of main:

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

And you must replace range(x) by range(len(x)) in the Iter_Replace function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.