How to get the number of dimensions of a matrix using numpy in python ?

Published: October 17, 2019

DMCA.com Protection Status

Exemple de comment déterminer le nombre de dimensions d'une matrice en python:

Get the number of dimensions of a matrix

Let's consider the following matrix:

>>> import numpy as np
>>> A = np.array([[3,9,4],[5,8,1],[9,2,5]])
>>> A
array([[3, 9, 4],
       [5, 8, 1],
       [9, 2, 5]])

To get the shape of the matrix, a solution is to first use shape:

>>> A.shape
(3, 3)

and then get the number of dimensions of the matrix using len:

>>> len(A.shape)
2

Example

Let's consider a matrix of dimension 1 or 2

Transpose the matrix if the dimension of the matrix = 2 and the number of columns > number of lines:

>>> def data_preparation(input_x):
...     input_x_shape = input_x.shape
...     if len(input_x_shape) == 2:
...             if input_x_shape[1] > input_x_shape[0]: 
...                     input_x = input_x.T
...     return input_x
... 
>>> input_x = np.arange(9)
>>> input_x
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> data_preparation(input_x)
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> input_x = np.arange(20)
>>> input_x = input_x.reshape(2,10)
>>> data_preparation(input_x)
array([[ 0, 10],
       [ 1, 11],
       [ 2, 12],
       [ 3, 13],
       [ 4, 14],
       [ 5, 15],
       [ 6, 16],
       [ 7, 17],
       [ 8, 18],
       [ 9, 19]])
>>>

References

Links Site
shape scipy doc
size scipy doc
what does numpy ndarray shape do? stackoverflow
Python len() programiz.com