filtering a 3D numpy array according to 2D numpy array

前端 未结 2 1182
孤街浪徒
孤街浪徒 2021-01-06 18:46

I have a 2D numpy array with the shape (3024, 4032).

I have a 3D numpy array with the shape (3024, 4032, 3).

2D numpy array is filled with 0s and 1s.

<
相关标签:
2条回答
  • 2021-01-06 19:30

    Ok, I'll answer this to highlight one pecularity regarding "missing" dimensions. Lets' assume a.shape==(5,4,3) and b.shape==(5,4)

    When indexing, existing dimensions are left aligned which is why @Divakar's solution a[b == 0] = 0 works.

    When broadcasting, existing dimensions are right aligned which is why @InvaderZim's a*b does not work. What you need to do is a*b[..., None] which inserts a broadcastable dimension at the right

    0 讨论(0)
  • 2021-01-06 19:46

    I think this one is very simple:

    If a is a 3D array (a.shape == (5, 4, 3)) filled with values, and b is a 2D array (b.shape == (5, 4)) filled with 1 and 0, then reshape b and multiply them:

    a = a * b.reshape(5, 4, 1)
    

    Numpy will automatically expand the arrays as needed.

    0 讨论(0)
提交回复
热议问题