Data Types In Numerical Python
In this article we discuss numpy data types with examples to more efficiently fulfill Python developer’s requirements.
NumPy Data Types
NumPy has several data types, which are data types with a single character, for example i for integers and u for unsigned integers.
Before we discuss NumPy datatypes, let’s review Python’s default data types:
- strings – Quote marks are utilized to display text data. For example, “mrexamples”.
- integer – Numbers that are displayed as integers. For example, 7, -7.
- float – A number that describes a real number. For example, 4.33, 78.346.
- boolean – A True or False value is utilized to describe it.
- complex – Describe complex numbers. For example, 4 + 72j or 3.24 + 6.11j.
Here is a list of NumPy’s data types and the characters that identify each type.
- b – boolean.
- c – complex float.
- f – float.
- i – integer.
- u – unsigned integer.
- m – timedelta.
- M – datetime.
- O – object.
- S – string.
- U – unicode string.
- V – Memory block remains the same for other types ( void ).
Array Data Type Check
A NumPy array object has an attribute known as dtype that displays the numpy data type of the array.
Find out what data type an array object has:
Example: 1 
Example: 2 
An array having strings can be characterised by its data type:
Example: 3 
Example: 4 
Defined Data Types For Arrays
For numpy data types, we utilize the array() function to generate arrays.
This function can accept an additional argument: dtype, which indicates the expected data type associated with the array items.
Arrays with string data types are generated as follows:
Example: 1 
Example: 2 
We can also set sizes for i, u, f, S, and U.
Assign data types 2 bytes integer to an array:
Example: 3 
Example: 4 
Can’t change a value?
When it comes to numpy data types, NumPy throws a Value Error if data fails to be cast.
ValueError: When a function receives an unexpected or invalid argument type, a ValueError is thrown.
It is not possible to transform a non-integer string like ‘mrexamples’ to an integer (will throw an exception):
Example: 
Example: 
Example: 
Existing Arrays Can Be Converted
As far as numpy data types are concerned, the best way to modify the type of an array is to copy it and execute the astype() method.
By passing the data type as a parameter, the astype() function makes a copy of the array.
Data types can be defined utilizing a string, such as ‘s‘ for string, ‘i‘ for integer, etc., or utilizing the data type directly, such as float for float and int for integer.
You can convert the data type from float to integer by setting the parameter value ‘i‘:
Example: 
Example: 
By passing int as the parameter value, you can transform the data type from float to integer:
Example: 
Example: 
To transform numpy data type from integer to boolean, follow the below examples: