Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 309
Saullo G. P. Castro Avatar asked Aug 13 '13 10:08

Saullo G. P. Castro


People also ask

What is the use of NDIM () function?

NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.

What is NDIM function in Python?

ndim() function return the number of dimensions of an array.

What does NDIM mean in NumPy?

In NumPy the number of dimensions is referred to as rank. The ndim is the same as the number of axes or the length of the output of x.shape. >>> x.

How do you find the minimum value in NumPy?

For finding the minimum element use numpy. min(“array name”) function.


2 Answers

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.

like image 104
seberg Avatar answered Oct 28 '22 10:10

seberg


You can use np.atleast_1d, np.atleast_2d and np.atleast_3d. Unfortunately I don't think there's currently an N-dimensional version.

like image 21
ali_m Avatar answered Oct 28 '22 11:10

ali_m