In Matlab, I can do the following:
X = randn(25,25,25);
size(X(:,:))
ans =
25 625
I often find myself wanting to quickly collapse the trailing dimensions of an array, and do not know how to do this in numpy.
I know I can do this:
In [22]: x = np.random.randn(25,25,25)
In [23]: x = x.reshape(x.shape[:-2] + (-1,))
In [24]: x.shape
Out[24]: (25, 625)
but x.reshape(x.shape[:-2] + (-1,)) is a lot less concise (and requires more information about x) than simply doing x(:,:).
I've obviously tried the analogous numpy indexing, but that does not work as desired:
In [25]: x = np.random.randn(25,25,25)
In [26]: x[:,:].shape
Out[26]: (25, 25, 25)
Any hints on how to collapse the trailing dimensions of an array in a concise manner?
Edit: note that I'm after the resulting array itself, not just its shape. I merely use size() and x.shape in the above examples to indicate what the array is like.
x.shape[:-2]would yield an empty tuple. (Adding-1to it means the array would be "flattened" into a 15625-length array.) I'm guessing you meantx.shape[0]?x.shape[:-2]returnsx.shapeup to (but not including) the second-to-last element. So for a 3D-arrayx, it returns just the first element ofx.shape. I used[:-2]rather than[0]because I'm looking for a general solution that works for all ND arrays where N>2.