NUMPY DATA TYPES
In this tutorial, we are going to learn about different numpy data types followed by how we can convert an existing numpy array to a different data type along with creating a numpy with a predefined data type array.
Numpy Data Types
Everytime you create an ndarray object (array), it’s always going to be associated with a certain type of data which decides what data type the array will have. Numpy supports the following data types:
Data type | Description |
bool_ | Boolean stored as a byte. |
int_ | Default integer type. |
intc | Identical to C int. |
intp | Integer used for indexing. |
int8 | Byte. |
int16 | Integer. |
int32 | Integer. |
int64 | Integer. |
uint8 | Unsigned integer. |
uint16 | Unsigned integer. |
uint32 | Unsigned integer. |
uint64 | Unsigned integer |
float_ | Shorthand for float64. |
float16 | Half precision float. |
float32 | Single precision float. |
float64 | Double precision float. |
complex_ | Shorthand for complex128. |
complex64 | Complex number, |
complex128 | Complex number, |
Syntax of Datatype
Let’s say you have an array to be converted to the required data type, then you need to provide with the required syntax of changing the data:
dtype(obj, align=False, copy=False)
So, let’s say we have an array of integers by default and we want to convert it to float data type.
arr = np.arange(10).reshape(2,5) arr
Output:
array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
Now, let’s convert it to float datatype
arr = np.dtype(float) arr
Output:
dtype('float64')
As you can see now the data type is float64 (it can be float32 as well depending on your system).
You can convert the array to different data types based on your needs. You can even predefined the array data type before printing the array
arr = np.array([1,2,3,4,5], dtype=float) arr
Output:
array([1., 2., 3., 4., 5.])
References: https://www.w3resource.com/