user14148145
user14148145

Reputation:

Iterate and replace values through a numpy array Python

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

Upvotes: 1

Views: 2128

Answers (2)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

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

Upvotes: 1

jlesuffleur
jlesuffleur

Reputation: 1253

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.

Upvotes: 0

Related Questions