【问题标题】:Iterate and replace values through a numpy array Python通过numpy数组Python迭代和替换值
【发布时间】:2021-03-12 10:47:33
【问题描述】:

我正在寻找创建一个随机维度的 numpy 数组,例如每 10 个迭代和替换值。

我试过了:

# 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()

但是我收到了这个错误:

TypeError: only integer scalar arrays can be converted to a scalar index

【问题讨论】:

  • 如果x 是数组,range(x) 没有意义。你想做什么?
  • 你好@hpaulj。 Cyttorak 明白我的问题。事实上,我想每 10 个替换数组中数组的所有值。

标签: python arrays numpy


【解决方案1】:

为此有一个numpy 函数,numpy.fullnumpy.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]])

如果你想迭代你可以使用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]])

或者,使用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]])

【讨论】:

  • 谢谢伙计,你有我的问题,但打印返回:[[1 2 2] [1 4 3]]
  • 您需要将其分配回x,然后打印。 x = np.full_like(x, 10), print(x)
【解决方案2】:

你有两个错误。 main的第一行缺少括号:

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

并且您必须在Iter_Replace 函数中将range(x) 替换为range(len(x))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多