代码之家  ›  专栏  ›  技术社区  ›  Mad Physicist

Numpy在数组结束后的奇怪行为

  •  5
  • Mad Physicist  · 技术社区  · 5 年前

    通常,如果试图在numpy中分配超过数组末尾的元素,则不存在的元素将被忽略。

    >>> x = np.zeros(5)
    >>> x[3:6] = np.arange(5)[2:5]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: could not broadcast input array from shape (3) into shape (2)
    

    但是,如果仅分配了一个元素,则完全超过数组末尾的相同操作“成功”:

    >>> x[5:] = np.arange(5)[4:]
    >>> x[5:] = np.arange(5)[4:100]
    

    >>> x[5:] = np.arange(5)[3:]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: could not broadcast input array from shape (2) into shape (0)
    

    1 回复  |  直到 5 年前
        1
  •  6
  •   hpaulj    5 年前

    其余的是广播。3进不了2。2无法进入0。但是1可以进入任何领域,包括0。我们倾向于考虑将大小为1的维度复制到更大的维度,但复制到0也可以。