Function that guarantees a minimum number of dimensions (ndim) for a numpy.ndarray

arrays, numpy, python

Solution

There is `np.array(array, copy=False, subok=True, ndmin=N)`. `np.atleast_1d`, etc. actually use the reshape method, probably to better support some weird subclasses such as matrix.

For most slicing operations in 2-D you could actually use the matrix class, though I would strongly suggest limiting the usage to those few points in code where its features are heavly used.

Problem

There are many situations where slicing operations in 2D arrays produce a 1D array as output, example: ``` a = np.random.random((3,3)) # array([[ 0.4986962 , 0.65777899, 0.16798398], # [ 0.02767355, 0.49157946, 0.03178513], # [ 0.60765513, 0.65030948, 0.14786596]]) a[0,:] # array([ 0.4986962 , 0.65777899, 0.16798398]) ``` There are workarounds like: ``` a[0:1,:] # or a[0,:][np.newaxis,:] # array([[ 0.4986962 , 0.65777899, 0.16798398]]) ``` Is there any `numpy` built in function that transforms an input array to a given number of dimensions? Like: ``` np.minndim(a, ndim=2) ```

Original source