Deepseafish
V2EX  ›  问与答

如何在 numpy 中快速实现这样的操作

  •  
  •   Deepseafish · Jul 31, 2020 · 2355 views
    This topic created in 2137 days ago, the information mentioned may be changed or developed.

    通过一个 mask 得到数组中的某几位后,再通过 mask 恢复原来的位置,并在其余地方填充 0 。具体实例代码如下。

    除了遍历有没有更好方法?

    https://gist.github.com/SungYK/4a23c94c9eb6b275d3d2bd90a0b2a5dd

    2 replies    2020-07-31 13:20:38 +08:00
    Xs0ul
        1
    Xs0ul  
       Jul 31, 2020
    lz 的 mask = np.array([1,3,5,7]) 一般不叫 mask,叫 indices 比较合理

    mask 应该是
    mask = np.zeros_like(arr)
    mask[indices] = 1

    然后
    res = np.where(mask, arr, 0)
    ytterbium
        2
    ytterbium  
       Jul 31, 2020 via Android
    和 numpy 关系比较近的 pytorch 里有个 masked_scatter

    https://pytorch.org/docs/stable/tensors.html#torch.Tensor.masked_scatter

    比如,mask 和 val 都是 np.array 类型

    mask = [

    [0, 1, 0],

    [1, 0, 0],

    [1, 1, 0]

    ]

    val = [1, 2, 3, 4]

    x = torch.Tensor.masked_scatter(torch.from_numpy(mask), torch.from_numpy(val)).data.numpy()

    输出 x 为 np.array 类型

    x = [

    [0, 1, 0],

    [2, 0, 0],

    [3, 4, 0]

    ]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2787 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 09:34 · PVG 17:34 · LAX 02:34 · JFK 05:34
    ♥ Do have faith in what you're doing.