How to convert data types of arrays using NumPy in Python
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:
- integer (
int) - float (
f) - string (
str) - boolean (
bool) - unsigned integers (
u) - timedelta (
m) - datetime (
M) - object (
O) - Unicode (
U)
We can easily specify what type of data array we want with type codes.
Code example
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)
Code explanation
- We import
arrayfrom thenumpylibrary. - We use the
array()method to create an array. Then, we instruct the array to create a float data type, with thefto parameterdtype. We assign this to a variable we callmy_array. - We print the
my_arrayvariable. - We use the
dtypeproperty to check for the data type.
How to convert data types for existing arrays
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.
Syntax
array.astype(typcode)
Parameters
The astype() method takes the typecode value as its only parameter value.
Code example
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)
Code explanation
-
Line 1: We import
arrayfrom thenumpymodule. -
Line 4: We use the
array()method to create a float type of the array and assign it to a variable calledmy_array. -
Line 7: We use the
astype()method to change themy_arrayarray from a float type to an integer type and assign the value to a new variable callednew_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 thedtypemethod.
Note: We can convert a type of array to another type by using the
astype()method and passing thetypecodeof the new array type that we want as the parameter value.