Reputation: 1056
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)
Upvotes: 0
Views: 1739
Reputation: 1056
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]]])
Upvotes: 1
Reputation: 205
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]]]
Upvotes: 0