In this article we are going to discuss about the different types of NumPy data types.
most of the data types in python are the same as those we mentioned in the earlier articles. Some of which are: strings, floats, integers, complex, Boolean and complex.
But coming to NumPy, we have a great variety of numerical data types. These data types are represented with their first letters: The table below gives shows some of the different types of NumPy data types
How to check the data types of an array
Just like in creating NumPy arrays, we used different functions. NumPy data types also have a function called dtype that we can used to check the datatype used in a function. The output returned is the data type used in a code or a program.
Example
import numpy as nparr = np.array([4, 8, 12, 16])print(arr.dtype)
OUTPUT
import numpy as nparr = np.array(['ana', 'kesso', 'georgette'])print(arr.dtype)
Create an array with a specific data type
In NumPy, we are able to convert data types into arrays, sequence of python numbers into their data types. Some of which are accepted by dtype NumPy function as arguments. These arguments are the target types
Example
import numpy as nparr = np.array([4, 8, 12, 16], dtype='i4')print(arr)print(arr.dtype)
OUTPUT
As we have seen in the output, the data of type that we have now is “int32”.
Let’s take a case where a value cannot to be converted to data. This mostly happened when the argument is incorrect.
Example
import numpy as nparr = np.array(['v', '2', '3'], dtype='i')
OUTPUT
To convert the data type of an array, we can use the preferable method which is the astype method. We can also the type itself.
That being said, we are going to see how to convert existing arrays to data type. We are going to use the astype.
We are going to the take given the array and convert it to the data type that we want.
This method allows you to input parameters of the type of data type you want and make duplicate of them. These parameters are the first letters of each of the data type of data.
For example: 'f' for float, ‘i’ for integer. Another way is just by using the data types directly.
Let’s take an example where we are able to change the data type to float, by using ‘I’ as parameter.
Example
import numpy as nparr = np.array([2.5, 3.5, 4.5])newarr = arr.astype(int)print(newarr)print(newarr.dtype)
OUTPUT
Let’s take an example where we able to convert an integer to a Boolean expression.
import numpy as nparr = np.array([2, 0.5, 9])newarr = arr.astype(bool)print(newarr)print(newarr.dtype)
OUTPUT







Comments
Post a Comment
Please do not enter any spam link in the comment box.