首页 > 解决方案 > 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

标签: pythonarraysnumpy

解决方案


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

推荐阅读