Let us discuss.
Size Property
NumPy provides the size property in an array that allows you to fetch the total number of elements within the specified array variable.
Consider the example code shown below:
arr = np.array([1,2,3,4,5])
print(f"size: {arr.size}")
In the above code, we start by importing the numpy package with the alias of np.
Next, we create a one-dimensional array holding five elements. Then, using the arr.size property, we fetch the size of the array as shown in the output below:
Although the size property works great for one-dimensional arrays, it falls back short for multi-dimensional arrays.
The code below illustrates this:
print(f"size: {arr.size}")
The code above uses the size property to fetch the size of a 2d array. The resulting value is as shown below:
Although it does return the total number of elements in the provided array, it does not accurately depict the size of the 2D array.
NumPy Shape()
To solve the issue encountered with the size property, we need to use the shape() function.
The shape() function is beneficial as it returns the number of elements in the provided array in each dimension.
This makes it handy when working with multi-dimensional arrays as it returns a tuple with the number of elements in each dimension. For example, in a 2D array, the function should return the number of elements in the form (x, y), where x is the number of elements in the rows and y is the number of elements in the column.
Consider the previous example:
print(f"size: {np.shape(arr)}")
In this case, the function should return:
We have an array with two rows and three columns in this case.
This gives a more accurate depiction of the shape and size of the provided array.
The same case applies to 3d arrays. An example is shown below:
print(f"size: {np.shape(arr)}")
The above code should return the array shape as:
Conclusion
In this article, we discussed NumPy array sizes and how to use various NumPy properties and functions to get the size and shape of an array.
Thanks for reading & See you in the next one!!