代码之家  ›  专栏  ›  技术社区  ›  Yuki Hashimoto

`添加到二维数组

  •  1
  • Yuki Hashimoto  · 技术社区  · 6 年前

    我在找二维版本的 np.add.at() .

    预期行为如下。

    augend = np.zeros((10, 10))
    indices_for_dim0 = np.array([1, 5, 2])
    indices_for_dim1 = np.array([5, 3, 1])
    addend = np.array([1, 2, 3])
    
    ### some procedure substituting np.add.at ###
    
    assert augend[1, 5] == 1
    assert augend[5, 3] == 2
    assert augend[2, 1] == 3
    

    任何建议都有帮助!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Mad Physicist    6 年前

    你可以使用 np.add.at 从多维角度看。这个 indices 参数在描述中包含以下内容:

    ……如果第一个操作数有多个维度,则索引可以是类似于索引对象或切片的数组元组。

    所以:

    augend = np.zeros((10, 10))
    indices_for_dim0 = np.array([1, 5, 2])
    indices_for_dim1 = np.array([5, 3, 1])
    addend = np.array([1, 2, 3])
    np.add.at(augend, (indices_for_dim0, indices_for_dim1), addend)
    

    更简单地说:

    augend[indices_for_dim0, indices_for_dim1] += addend
    

    如果您真的担心多维方面,并且您的前兆是普通的连续C顺序数组,那么可以使用 ravel ravel_multi_index 要在一维视图上执行操作,请执行以下操作:

    indices = np.ravel_multi_index((indices_for_dim0, indices_for_dim1), augend.shape)
    raveled = augend.ravel()
    np.add.at(raveled, indices, addend)
    
        2
  •  1
  •   Chris    6 年前

    Oneliner:

    np.add.at(augend, (indices_for_dim0, indices_for_dim1), addend)
    augend
    array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
           [0., 3., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 2., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
    
    assert augend[1, 5] == 1
    assert augend[5, 3] == 2
    assert augend[2, 1] == 3
    # No AssertionError
    

    当使用二维数组 np.add.at , indices 必须是元组,其中 tuple[0] 包含所有第一个坐标和 tuple[1] 包含所有第二个坐标。