【问题标题】:numpy array assign values from another arraynumpy 数组从另一个数组赋值
【发布时间】:2018-02-10 18:37:47
【问题描述】:

如果我这样做:

import numpy as np
b=np.array([1,2,3,4,5])
c=np.array([0.6,0.7,0.8,0.9])
b[1:]=c

我得到 b =

array([1,0,0,0,0])

如果 c 只包含整数,它可以正常工作。但我有分数。 我希望得到这样的东西:

array([1,0.6,0.7,0.8,0.9])

我怎样才能做到这一点?

【问题讨论】:

    标签: python arrays python-3.x numpy


    【解决方案1】:

    Numpy 数组是强类型的。确保您的数组具有相同的类型,如下所示:

    import numpy as np
    
    b = np.array([1, 2, 3, 4, 5])
    c = np.array([0.6, 0.7, 0.8, 0.9])
    
    b = b.astype(float)
    b[1:] = c
    
    # array([ 1. ,  0.6,  0.7,  0.8,  0.9])
    

    如果您愿意,您甚至可以从其他数组传递类型,例如

    b = b.astype(c.dtype)
    

    【讨论】:

    • 或:b.astype(c.dtype)
    【解决方案2】:

    如果您不知道类型是否匹配,则使用.astype 并将copy 标志设置为False 或使用np.asanyarray 更经济:

    >>> b_float = np.arange(5.0)
    >>> b_int = np.arange(5)
    >>> c = np.arange(0.6, 1.0, 0.1)
    >>> 
    
    >>> b = b_float.astype(float)
    # astype makes an unnecessary copy
    >>> np.shares_memory(b, b_float)
    False
    
    # avoid this using the copy flag ...
    >>> b = b_float.astype(float, copy=False)
    >>> b is b_float
    True
    
    # or asanyarray
    >>> b = np.asanyarray(b_float, dtype=float)
    >>> b is b_float
    True
    
    # if the types do not match the flag has no effect
    >>> b = b_int.astype(float, copy=False)
    >>> np.shares_memory(b, b_int)
    False
    
    # likewise asanyarray does make a copy if it must
    >>> b = np.asanyarray(b_int, dtype=float)
    >>> np.shares_memory(b, b_int)
    False
    

    【讨论】:

      【解决方案3】:

      b=np.array([1,2,3,4,5]) 将元素存储为 整数 而不是 b=np.array([1,2,3,4,5]).astype(float) 将元素存储为 float 然后执行b[1:]=c

      【讨论】:

        【解决方案4】:

        问题在于类型转换。在重新分配项目之前,最好让两个数组的类型相同。如果不可能,您可以使用另一个函数来创建您想要的数组。在这种情况下你可以使用np.concatenate():

        In [16]: np.concatenate((b[:1], c))
        Out[16]: array([ 1. ,  0.6,  0.7,  0.8,  0.9])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-03
          • 1970-01-01
          • 2020-10-10
          • 2021-01-31
          • 2011-03-04
          • 2013-02-08
          相关资源
          最近更新 更多