numpy arrays modified by other arrays

Viewed 44

I am having a hard time understanding what is wrong with the output of this very simple numpy code

fake=np.arange(0,24).reshape(4,2,3)
print("The original array")
print(fake)
out=np.copy(fake)
print("the copy")
print(out)
print("what part we want to modify ")
print(fake[:,:,2])
print(fake[:,:,2]<5)
print("after the modification")
out[fake[:,:,2]<5]=0
print(out)

which shows as output

The original array
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]

 [[12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]]]
the copy
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]

 [[12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]]]
what part we want to modify 
[[ 2  5]
 [ 8 11]
 [14 17]
 [20 23]]
[[ True False]
 [False False]
 [False False]
 [False False]]
after the modification
[[[ 0  0  0]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]

 [[12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]]]

I mean why? why the first element becomes [0,0,0]? Isn't is supposed to become [0,1,0]? after all the condition is only affecting

[[ 2  5]
 [ 8 11]
 [14 17]
 [20 23]]

Can someone help me understand this?

1 Answers

Notice that the shape of out is (4, 2, 3) and the shape of fake[:, :, 2] < 5 is (4, 2) so calling the line out[fake[:, :, 2] < 5] = 0 puts 0s in every cell in the last dimension. What you want instead is this:

out[fake[:, :, 2] < 5, 2] = 0
Output:
[[[ 0  1  0]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]

 [[12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]]]

Related