In Python, an array is used to store multiple items of the same type. All the elements of an array must be of the same type. Arrays are handled by a module called Numpy
.
The data types in Numpy
and their respective type codes include:
int
)f
)str
)bool
)u
)m
)M
)O
)U
)We can easily specify what type of data array we want with type codes.
from numpy import array# crreating the bool datatype of an arraymy_array = array([1, 2, 3, 4, 5], dtype = 'f')print(my_array)print(my_array.dtype)
array
from the numpy
library.array()
method to create an array. Then, we instruct the array to create a float data type, with the f
to parameter dtype
. We assign this to a variable we call my_array
.my_array
variable.dtype
property to check for the data type.We make a copy of the array and use the array.astype()
method to change its data type. After doing this, we can easily specify the new data type of the array we want.
array.astype(typcode)
The astype()
method takes the typecode
value as its only parameter value.
Let’s convert a float type of an array to an integer(i
) type.
from numpy import array# creating a float type of arraymy_array = array([3.1, 2.1, 1.5])# converting the old array to an integer typenew_array = my_array.astype('i')print(new_array)# to check the data type of array we createdprint(new_array.dtype)
Line 1: We import array
from the numpy
module.
Line 4: We use the array()
method to create a float type of the array and assign it to a variable called my_array
.
Line 7: We use the astype()
method to change the my_array
array from a float type to an integer type and assign the value to a new variable called new_array
.
Line 9: We print the new variable, new_array
.
Line 12: We check for the data type of the new array, new_array
, which we created with the dtype
method.
Note: We can convert a type of array to another type by using the
astype()
method and passing thetypecode
of the new array type that we want as the parameter value.