How to practice with .dtype and .shape in Numpy?
Numpy has attributes for arrays. These attributes describes the structure and the content. These are given below…
- · .dtype
- · .shape
.dtype:
It means ‘data
type’. It gives the information about the values to be stored in the array.
eg. Integers,floats,strings.
.shape:
It
provides the dimensions of the array. It may be of single dimensional, two
dimensional or three dimensional.
Let us create python program to implement using Numpy.
Sample Python Numpy code for .dtype:
# Example 1: Integer array
Import numpy as np
s_int = np.array([11, 22, 33, 44])
print("Array Elements:", s_int)
print("Data type of the Array is:", s_int.dtype)
Output:
Array Elements: [11 22 33 44]
Data type of the Array is: int64
# Example 2: Float array
Import numpy as np
s_float = np.array([2.2, 3.8, 7.6])
print("Array Elements:", s_float)
print("Data type of the Array is:", s_float.dtype)
Output:
Array Elements: [2.2 3.8 7.6]
Data type of the Array is: float64
# Example 3: Mixed types (NumPy will upcast)
Import numpy as np
s_mixed = np.array([1, 2.5, 3, 7.8, 'a'])
print("Array Elements:", s_mixed)
print("Data type of the Array is:", s_mixed.dtype)
Output:
Array Elements: ['1' '2.5' '3' '7.8' 'a']
Data type of the Array is: <U32
Next one is about .shape
.shape:
It describes
about dimensions.
#Single dimensional array
import numpy as np
arr1 = np.array([11, 22, 33, 44, 55])
print("Shape:", arr1.shape)
Output:
Shape: (5,)
#Two Dimensional array
import numpy as np
arr2 = np.array([[11, 22, 33], [44, 55, 66]])
print("Shape:", arr2.shape)
Output:
Shape: (2, 3)
#Three Dimensional array
import numpy as np
arr3 = np.array([[[11, 22, 12], [33, 44, 45]], [[55, 66, 56],
[77, 88, 89]]])
print("Shape:", arr3.shape)
Output:
Shape: (2, 2, 3)
Hope, this code is useful to you. It is very important to
know about .dtype and .shape while starting python numpy code. Keep Coding!!!
Comments
Post a Comment