Examples of how to get the number of elements in an array (or matrix) with numpy in python
Create a matrix
Let's create a simple matrix to illustrate how to get the number of elements
import numpy as np
A = np.random.randint(5, size=(4, 6))
print(A)
returns
[[3 0 0 4 3 3]
[4 2 3 4 2 2]
[0 1 1 4 1 0]
[4 3 0 0 3 3]]
Get the number of elements using size
To get the number of elements in the matrix A, a solution is to use the method size:
print(A.size)
24
Get the number of elements using shape
print(A.shape[0]*A.shape[1])
24
Get the number of unique elements
To go further we can also get unique elements inside the matrix A:
print(np.unique(A))
returns
[0 1 2 3 4]
and then print the number for each unique element:
for e in np.unique(A):
print('Number of {}: '.format(e), A[A==e].size)
returns
Number of 0: 6
Number of 1: 3
Number of 2: 3
Number of 3: 7
Number of 4: 5