Shape, Size, ndim, and dtype in NumPy Framework

NumPy provides various attributes to understand the structure and properties of an array. This tutorial covers shape, size, ndim, and dtype with examples.

1. Checking the Shape of an Array: shape

The shape attribute returns a tuple indicating the number of elements along each dimension.

            import numpy as np
            
            arr = np.array([[1, 2, 3], [4, 5, 6]])
            print("Shape of array:", arr.shape)
        

Output:

            Shape of array: (2, 3)
        

2. Checking the Size of an Array: size

The size attribute returns the total number of elements in the array.

            print("Total number of elements:", arr.size)
        

Output:

            Total number of elements: 6
        

3. Checking the Number of Dimensions: ndim

The ndim attribute returns the number of dimensions (axes) of the array.

            print("Number of dimensions:", arr.ndim)
        

Output:

            Number of dimensions: 2
        

4. Checking the Data Type of Elements: dtype

The dtype attribute shows the data type of elements stored in the array.

            print("Data type of array:", arr.dtype)
        

Output:

            Data type of array: int64 (varies based on system)
        

Conclusion

NumPy provides essential properties such as shape, size, ndim, and dtype to analyze arrays efficiently. These attributes help in understanding the structure of an array and its data.





Advertisement