代码之家  ›  专栏  ›  技术社区  ›  Majoris

用固定值预填充numpy数组

  •  0
  • Majoris  · 技术社区  · 2 年前

    在初始化具有固定值的numpy数组时,如何进行预填充? 我试着生成 list 并将其用作 fill

    >>> c = np.empty(5)
    >>> c
    array([0.0e+000, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323])
    >>> np.array(list(range(0,10,1)))
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> 
     
    >>> c.fill(np.array(list(range(0,10,1))))
    TypeError: only length-1 arrays can be converted to Python scalars
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: setting an array element with a sequence.
    
    >>> c.fill([np.array(list(range(0,10,1)))])
    TypeError: float() argument must be a string or a real number, not 'list'
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: setting an array element with a sequence.
    

    预期-

    array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
    
    2 回复  |  直到 2 年前
        1
  •  2
  •   Simon Lundberg    2 年前

    fill 用相同的值填充每个条目。 c = np.empty(size); c.fill(5) 分配大小为的数组 size 不初始化任何值,然后用所有值填充 5

    除了AJ Biffl的答案外,您还可以通过广播为ndarray赋值:

    c = np.empty(5)
    c[:] = range(5)
    

    这只适用于形状匹配的情况,但它确实可以让你做这样的事情:

    a = np.empty((5, 3))
    a[:] = [range(i, i+3) for i in range(5)]
    
    >>> array([[0., 1., 2.],
           [1., 2., 3.],
           [2., 3., 4.],
           [3., 4., 5.],
           [4., 5., 6.]])
    
        2
  •  1
  •   AJ Biffl    2 年前

    np.tile(np.arange(10), (5,1))

    np.arange(10) 创建一个0到9的整数数组

    np.tile(..., (5,1)) 平铺阵列的副本-5个副本“向下”(新行)和1个副本“横向”(每行1个副本)