简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM