Reputation: 1964
I have a numpy matrix in the middle of a running program (let's say it's name is rdy
). I found that reshape it into a one-dimensional matrix gives me a two-dimensional matrix. But if I try the same thing in the interactive shell, I get the expected results. Like the following ipython logs. I'm wondering which aspect of the matrix rdy cause it to behave differently when reshaping?
# This is expected:
In [191]: np.random.rand(512, 1).reshape(-1).shape
Out[191]: (512,)
# This is unexpected:
In [192]: rdy.reshape(-1).shape
Out[192]: (1, 512)
# The following are the different aspects of the rdy matrix:
In [193]: rdy.shape
Out[193]: (512, 1)
In [194]: rdy.flags
Out[194]:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
In [195]: rdy.data
Out[195]: <read-write buffer for 0xeae6488, size 4096, offset 0 at 0x2ff95e70>
Upvotes: 3
Views: 517
Reputation: 10224
One of the key defining properties of a np.matrix
is that it will remain as a two-dimensional object through common transformations. (After all, that's almost the definition of a matrix.)
np.random.rand
returns an np.ndarray
, which does not share this property. (I like to think of an ndarray as very similar to a C array, in that you can change the 'dimensions' all you like, and so long as you're still looking at the same region of memory, and not overstepping bounds, all will be well.)
If you want the matrix to behave as an array, you can convert it to one.
Upvotes: 2