6

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.

3D numpy array is filled with values between 0 and 255.

By looking at the 2D array values, I want to change the values in 3D array. If a value in 2D array is 0, I will change the all 3 pixel values in 3D array into 0 along the last axes. If a value in 2D array is 1, I won't change it.

I have checked this question, How to filter a numpy array with another array's values, but it applies for 2 arrays which have same dimensions. In my case, dimensions are different.

How the filtering is applied in two arrays, with same size on 2 dimensions, but not size on the last dimension?

2
  • I will change the pixel value in 3D array into 0 - All three values along the last axis? Commented Nov 21, 2017 at 8:34
  • second_arr[first_arr==0] = 0? Commented Nov 21, 2017 at 8:38

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Did either you or OP who accepted this answer actually test it?
Thought I checked, but seems like I did not. Edited. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.