0

I am trying to set certain values of an array to 0. I have a larger array with many different values but want to set a random square/rectangle subset of values to zero.

a = np.array([[[1,1,1],[2,2,2],[3,3,3]],[[4,4,4],[5,5,5],[6,6,6]],[[7,7,7],[8,8,8],[9,9,9]]])
b = np.zeros((2,2,3)) 
#combination function

Expected Result:

combination = 
array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]],

       [[4, 4, 4],
        [0, 0, 0],
        [0, 0, 0]],

       [[7, 7, 7],
        [0, 0, 0],
        [0, 0, 0]]])

I know this is wrong but, I tried just multiplying them like this but got an error:

masked = a*b
ValueError: operands could not be broadcast together with shapes (3,3,3) (2,2,3)
2
  • 1
    Instead of multiplication why don't you think about if it would be possible to assign a random square/rectangle to 0? Commented Feb 14, 2021 at 5:05
  • 1
    I'd look at using index slicing for this instead of a boolean mask. The Value Error is caused by a shape mismatch. multiplying ndarrays requires same shapes. I think your question requires some clarity: you are using a 3d array yet you want to find squares and not cubes? Slice example a[0, np.arange(3)] = 0 Commented Feb 14, 2021 at 5:13

2 Answers 2

1

Thanks to @Naman and @bcr for hints. Slicing is the best method

>>> a = np.array([[[1,1,1],[2,2,2],[3,3,3]],[[4,4,4],[5,5,5],[6,6,6]],[[7,7,7],[8,8,8],[9,9,9]]])
>>> a[1:3,1:3,]=0 
>>> a
array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]],

       [[4, 4, 4],
        [0, 0, 0],
        [0, 0, 0]],

       [[7, 7, 7],
        [0, 0, 0],
        [0, 0, 0]]])
Sign up to request clarification or add additional context in comments.

Comments

0

Numpy arrays use dimensions so two arrays can only be operated on if they have the same dimensions. You can find the dimension of an ndarray by using:

array.shape()

The dimension of an array is essentially its structure, for example:

>>> array = np.zeros((3,2))
>>> print(array)
>>> [[0, 0],
     [0, 0],
     [0, 0]]

As you can see in the previous example, the shape of the ndarray corresponds to its dimension--in this case it contains 3 subarrays with 2 elements each. Back to your question, in order for you to run an operation on 2 ndarrays, they need to have the same dimension, which in your example they do not. Try setting b to the same size as a with:

b = np.zeros((3, 3, 3))

Then your code should work as expected:

>>> a = np.array([[[1,1,1],[2,2,2],[3,3,3]],[[4,4,4],[5,5,5],[6,6,6]],[[7,7,7],[8,8,8],[9,9,9]]])
>>> b = np.zeros((3,3,3)) 
>>> print(a * b)
>>> [[[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]]]

Comments

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.