[Numpy-discussion] mixing arrays and matrices: squeeze yes, flattened no?

Christopher Barker Chris.Barker at noaa.gov
Tue Feb 21 16:56:01 CST 2006

Sven Schreiber wrote:
>>>>> a = N.ones((5,10))
>>>>> a[:,1].shape # an index: it reduces the rank
>> (5,)
>>>>> a[:,1:2].shape # a slice: it keeps the rank
>> (5, 1)
> That's very interesting, thanks. But I find it a little
> unintuitive/surprising, so I'm not sure if I will use it. I fear that I
> wouldn't understand my own code after a while of not working on it.

Well, what's surprising to different people is different. However....

> I guess I'd rather follow the advice and just remember to treat 1d as a row.

Except that it's not, universally. For instance, it won't transpose:

 >>> a = N.ones((5,))
 >>> a.transpose()
array([1, 1, 1, 1, 1])
 >>> a.shape = (1,-1)
 >>> a
array([[1, 1, 1, 1, 1]])
 >>> a.transpose()

so while a rank-1 array is often treated like a row vector, it really 
isn't the same. The concept of a row vs a column vector is a rank-2 
array concept -- so keep your arrays rank-2.

It's very helpful to remember that indexing reduces rank, and slicing 
keeps the rank the same. It will serve you well to use that in the 
future anyway.


Christopher Barker, Ph.D.
NOAA/OR&R/HAZMAT         (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov

More information about the Numpy-discussion mailing list