Massimo Lavermicocca
Massimo Lavermicocca

Reputation: 175

"Shape mismatch error" while swapping in numpy matrix

I am using python2.7 and numpy and I have the following matrix:

L = np.asmatrix([[0,1,2,3,4], [5,6,7,8,9]])

and I am trying to swap L[[0,1], 0] with L[[1,0], 0] but I have the error:

"shape mismatch: value array of shape (2,1) could not be broadcast to indexing result of shape (2,)"

I cannot understand this because if I print L[[0,1], 0] and L[[1,0], 0] they return

L[[0,1], 0] = matrix([[0]
                      [5]])
L[[1,0], 0] = matrix([[5]
                      [0]])

Anyway if I swap the entire row with L[[0,1], :] = L[[1,0], :] it works perfect but it isn't what I want to do.

Do you have any suggestion?

Upvotes: 0

Views: 61

Answers (1)

macroeconomist
macroeconomist

Reputation: 701

This seems to be an ugly behavior of the np.matrix class: if you write L[[0,1], 0] as an expression, you get a (two-dimensional) matrix back, but if you try to assign to L[[0,1], 0], NumPy wants you to give it something one-dimensional!

The immediate way to solve this is to write the expression on the left as a two-dimensional slice, replacing the 0 in the second dimension with a slice 0:1:

L[[0,1], 0:1] = L[[1,0], 0]

But you almost certainly just want to avoid using np.matrix entirely and just use np.array. The old NumPy matrix is an obsolete, someday-to-be-deprecated class. Arrays have the expected behavior, and you can just write this:

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

Out[1]: 
array([[5, 1, 2, 3, 4],
       [0, 6, 7, 8, 9]])

Upvotes: 1

Related Questions