NumPy Data Types

A data type is a way to specify the type of data that will be stored in an array. For example,

array1 = np.array([2, 4, 6])

Here, the array1 array contains three integer elements, so the data type is Integer(int64)), by default.

NumPy provides us with several built-in data types to efficiently represent numerical data.


NumPy Data Types

NumPy offers a wider range of numerical data types than what is available in Python. Here's the list of most commonly used numeric data types in NumPy:

  1. int8, int16, int32, int64 - signed integer types with different bit sizes
  2. uint8, uint16, uint32, uint64 - unsigned integer types with different bit sizes
  3. float32, float64 - floating-point types with different precision levels
  4. complex64, complex128 - complex number types with different precision levels

Check Data Type of a NumPy Array

To check the data type of a NumPy array, we can use the dtype attribute. For example,

In the above example, we have used the dtype attribute to check the data type of the array1 array.

Since array1 is an array of integers, the data type of array1 is inferred as int64 by default.


Example: Check Data Type of NumPy Array

Output

int64
float64
complex128

Here, we have created types of arrays and checked the default data types of these arrays using the dtype attribute.

  • int_array - contains four integer elements whose default data type is int64
  • float_array - contains three floating-point numbers whose default data type is float64
  • complex_array - contains three complex numbers whose default data type is complex128

Creating NumPy Arrays With a Defined Data Type

In NumPy, we can create an array with a defined data type by passing the dtype parameter while calling the np.array() function. For example,

Output

[1 3 7] int32

In the above example, we have created a NumPy array named array1 with a defined data type.

Notice the code,

np.array([1, 3, 7], dtype='int32')

Here, inside np.array(), we have passed an array [1, 3, 7] and set the dtype parameter to int32.

Since we have set the data type of the array to int32, each element of the array is represented as a 32-bit integer.


Example: Creating NumPy Arrays With a Defined Data Type

Output

[1 3 7] int8
[2 4 6] uint16
[1.2 2.3 3.4] float32
[1.+2.j 2.+3.j 3.+4.j] complex64

NumPy Type Conversion

In NumPy, we can convert the data type of an array using the astype() method. For example,

Output

[1 3 5 7] int64
[1. 3. 5. 7.] float64

Here, int_array.astype('float') converts the data type of int_array from int64 to float64 using astype().