1

In python, when I was trying to A -= something instead of A = A - something, it seems that there are something different if I do integer array indexing after the subtraction. The code is like this:

A = np.array([[1,2,3],[4,5,6]]) 
B = A - np.matrix(np.sum(A,axis = 1)).T
A -= np.matrix(np.sum(A,axis = 1)).T

If now I print A and B as a sanity check, they should be the same:

print(A)
print(B)
#[[ -5  -4 -3]
# [-11 -10 -9]]
#[[ -5  -4 -3]
# [-11 -10 -9]]

However, if now I do integer array indexing and print the shape of the result:

y = [0,2]
print(B[np.arange(N),y].shape)
print(A[np.arange(N),y].shape)
# the result is:
# (1,2)
# (2,)

I don't understand why the shapes of two identical matrices after indexing are different. Can anyone help me with it? Thank you!

  • Hi Chris, thank you for your reply! Does it means that -= will keep A as an array even if a matrix is subtracted from A, whereas (A - the matrix) will return a matrix instead of an array? – sugarconsumer Feb 18 '19 at 05:37
  • Possible duplicate of [How do numpy's in-place operations (e.g. \`+=\`) work?](https://stackoverflow.com/questions/16034672/how-do-numpys-in-place-operations-e-g-work) – Chris Feb 18 '19 at 06:01
  • Take a look at the above link, and if it doesn't clarify your problem, please let me know :) – Chris Feb 18 '19 at 06:04
  • Thank you Chris, it's crystal clear! – sugarconsumer Feb 21 '19 at 17:19

0 Answers0