Use .shape to obtain a tuple of array dimensions:
>>> a.shape
(2, 2)
Answer from Felix Kling on Stack OverflowHow do I find the length (or dimensions, size) of a numpy matrix in python? - Stack Overflow
How to correctly count (and think about) dimensions in a numpyarray
How can I find the dimensions of a matrix in Python? - Stack Overflow
Numpy: What's the point of producing arrays of shape (N,) instead of (N,1)? Super annoying feature.
Videos
Use .shape to obtain a tuple of array dimensions:
>>> a.shape
(2, 2)
First:
By convention, in Python world, the shortcut for numpy is np, so:
In [1]: import numpy as np
In [2]: a = np.array([[1,2],[3,4]])
Second:
In Numpy, dimension, axis/axes, shape are related and sometimes similar concepts:
dimension
In Mathematics/Physics, dimension or dimensionality is informally defined as the minimum number of coordinates needed to specify any point within a space. But in Numpy, according to the numpy doc, it's the same as axis/axes:
In Numpy dimensions are called axes. The number of axes is rank.
In [3]: a.ndim # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2
axis/axes
the nth coordinate to index an array in Numpy. And multidimensional arrays can have one index per axis.
In [4]: a[1,0] # to index `a`, we specific 1 at the first axis and 0 at the second axis.
Out[4]: 3 # which results in 3 (locate at the row 1 and column 0, 0-based index)
shape
describes how many data (or the range) along each available axis.
In [5]: a.shape
Out[5]: (2, 2) # both the first and second axis have 2 (columns/rows/pages/blocks/...) data
shape is a property of both numpy ndarray's and matrices.
A.shape
will return a tuple (m, n), where m is the number of rows, and n is the number of columns.
In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray
matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.
from https://www.w3schools.com/python/numpy/trypython.asp?filename=demo_numpy_ndim
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
--- output
0
1
2
3
---
Answers, explained:
-
a is just a number, so 0 dimensions
-
b is 1 row, so 1 dimension
-
c has 2 rows, so 2 dimensions.
but d ?
How do you correctly describe matrix d in words?
(deleted: d is 2 x 3 matrix, so why would d = 3?)
The number of rows of a list of lists would be: len(A) and the number of columns len(A[0]) given that all rows have the same number of columns, i.e. all lists in each index are of the same size.
If you are using NumPy arrays, shape can be used. For example
>>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
>>> a
array([[[ 1, 2, 3],
[ 1, 2, 3]],
[[12, 3, 4],
[ 2, 1, 3]]])
>>> a.shape
(2, 2, 3)