NumPy Attributes

An array's properties are critical to determining the shape, dimension of the array, item size, etc. If related to the numpy ndarray object, we can learn more about these in depth. Let's examine a few of these qualities along with the corresponding instances.

Now that we are knowledgeable about multidimensional arrays, we will examine techniques for programmatically examining an array's characteristics (e.g., its dimensionality). It is crucial to comprehend an array's " shape".

To establish the setting for our tutorial, we'll start by creating a basic numpy array.

Code

Output:

[[[2 4 7 8]
  [2 5 8 6]]

 [[3 8 6 4]
  [8 6 4 9]]

 [[2 9 6 8]
  [6 7 2 9]]]

The previous code indicates that it is a 3D array constructed this way.

  • Axis-0 decides which of the three sheets to choose.
  • Any sheet's Axis-1 determines which of its two rows should be chosen.
  • Axis 2 determines the four columns to choose from in any plane and row.

ndarray.shape

This property returns the array's dimension. The size of the NumPy array is indicated as a tuple of integer values. For instance, a matrix with n number of rows and m number of columns will have the shape of the form (n * m).

Code

Output:

[[[2 4 7 8]
  [2 5 8 6]]

 [[3 8 6 4]
  [8 6 4 9]]

 [[2 9 6 8]
  [6 7 2 9]]]
The shape of the array: 
(3, 2, 4)

We can change the shape of any numpy array by rearranging the shape tuple.

Code

Output:

The shape of the original array is:  (3, 2, 4)
The new shape of the array is:  (2, 2, 6)

ndarray.ndim

This feature makes it easier to determine how many dimensions any given NumPy array has. For instance, the number 1 denotes a 1D numpy array, the number 2 denotes a 2D numpy array, and so forth.

Code

Output:

The dimension of the array: 
3

ndarray.itemsize

This attribute makes it easier to determine the length of the numpy array in bytes of every element of the NumPy array. As an illustration, if your array contains integers, this feature will give 88 as integers and need 88 bits of memory.

Code

Output:

The itemsize of the array is:  8





Latest Courses