NumPy supports a much greater variety of numerical types than Python does. The following table shows different scalar data types defined in NumPy.

Sr.No. Data Types Description
1bool_Boolean (True or False) stored as a byte
2int_Default integer type (same as C long; normally either int64 or int32)
3intcIdentical to C int (normally int32 or int64)
4intpInteger used for indexing (same as C ssize_t; normally either int32 or int64)
5int8Byte (-128 to 127)
6int16Integer (-32768 to 32767)
7int32Integer (-2147483648 to 2147483647)
8int64Integer (-9223372036854775808 to 9223372036854775807)
9uint8Unsigned integer (0 to 255)
10uint16Unsigned integer (0 to 65535)
11uint32Unsigned integer (0 to 4294967295)
12uint64Unsigned integer (0 to 18446744073709551615)
13float_Shorthand for float64
14float16Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
15float32Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
16float64Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
17complex_Shorthand for complex128
18complex64Complex number, represented by two 32-bit floats (real and imaginary components)
19complex128Complex number, represented by two 64-bit floats (real and imaginary components)

NumPy numerical types are instances of dtype (data-type) objects, each having unique characteristics. The dtypes are available as np.bool_, np.float32, etc.

Data Type Objects (dtype)

A data type object describes interpretation of fixed block of memory corresponding to an array, depending on the following aspects:

  • Type of data (integer, float or Python object)
  • Size of data
  • Byte order (little-endian or big-endian)
  • In case of structured type, the names of fields, data type of each field and part of the memory block taken by each field.
  • If data type is a subarray, its shape and data type

The byte order is decided by prefixing < or > to data type. < means that encoding is little-endian (least significant is stored in smallest address). > means that encoding is big-endian (most significant byte is stored in smallest address).

A dtype object is constructed using the following syntax:

numpy.dtype(object, align, copy)

The parameters are:

  • Object: To be converted to data type object
  • Align: If true, adds padding to the field to make it similar to C-struct
  • Copy: Makes a new copy of dtype object. If false, the result is reference to builtin data type object

Example: Using Array-scalar Type

import numpy as np dt = np.dtype(np.int32) print(dt)

Output:

int32

Example: Using Equivalent String for Data Type

import numpy as np dt = np.dtype('i4') print(dt)

Output:

int32

Example: Using Endian Notation

import numpy as np dt = np.dtype('>i4') print(dt)

Output:

>i4

Example: Creating a Structured Data Type

import numpy as np dt = np.dtype([('age', np.int8)]) print(dt)

Output:

[('age', 'i1')]

Example: Applying Structured Data Type to ndarray

import numpy as np dt = np.dtype([('age', np.int8)]) a = np.array([(10,), (20,), (30,)], dtype=dt) print(a)

Output:

[(10,) (20,) (30,)]

Example: Accessing Field Content of Structured Data Type

import numpy as np dt = np.dtype([('age', np.int8)]) a = np.array([(10,), (20,), (30,)], dtype=dt) print(a['age'])

Output:

[10 20 30]

Example: Defining a Complex Structured Data Type

import numpy as np student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')]) print(student)

Output:

[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')]

Example: Applying Complex Structured Data Type to ndarray

import numpy as np student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')]) a = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student) print(a)

Output:

[('abc', 21, 50.0), ('xyz', 18, 75.0)]

Character Codes

Each built-in data type has a character code that uniquely identifies it.

  • 'b' − boolean
  • 'i' − (signed) integer
  • 'u' − unsigned integer
  • 'f' − floating-point
  • 'c' − complex-floating point
  • 'm' − timedelta
  • 'M' − datetime
  • 'O' − (Python) objects
  • 'S', 'a' − (byte-)string
  • 'U' − Unicode
  • 'V' − raw data (void)

Checking the Data Type of an Array

You can check the data type of an array using the dtype attribute. This attribute returns a dtype object, which describes the type of elements in the array:

import numpy as np a = np.array([1, 2, 3]) print(a.dtype)

Output:

int64

Create Arrays With Defined Data Type

In NumPy, you can explicitly specify the data type (dtype) of the elements in an array at the time of its creation.

We can use the dtype parameter in array creation functions (such as np.array(), np.zeros(), np.ones(), etc.) to define the data type of the array elements.

Example: Creating an Integer Array

import numpy as np # Creating an array of integers with a specified dtype a = np.array([1, 2, 3], dtype=np.int32) print("Array:", a) print("Data type:", a.dtype)

Output:

Array: [1 2 3] Data type: int32

Example: Creating a Complex Array

import numpy as np # Creating an array of complex numbers with a specified dtype c = np.array([1+2j, 3+4j, 5+6j], dtype=np.complex64) print("Array:", c) print("Data type:", c.dtype)

Output:

Array: [1.+2.j 3.+4.j 5.+6.j] Data type: complex64

Convert Data Type of NumPy Arrays

NumPy provides several methods to convert the data type of arrays:

  • astype() Method: It is the most commonly used method for type conversion.
  • numpy.cast() Functions: A set of functions provided by NumPy for casting arrays to different types.
  • In-place Type Conversion: Convert types directly while creating arrays.

Example: Using the "astype" Method

import numpy as np a = np.array([1, 2, 3, 4, 5]) print("Original array:", a) print("Original dtype:", a.dtype) # Converting to float a_float = a.astype(np.float32) print("Converted array:", a_float) print("Converted dtype:", a_float.dtype)

Output:

Original array: [1 2 3 4 5] Original dtype: int64 Converted array: [1. 2. 3. 4. 5.] Converted dtype: float32

Example: Using "numpy.int32" Function

import numpy as np d = np.array([1.1, 2.2, 3.3, 4.4, 5.5]) print("Original array:", d) print("Original dtype:", d.dtype) d_int = np.int32(d) print("Converted array:", d_int) print("Converted dtype:", d_int.dtype)

Output:

Original array: [1.1 2.2 3.3 4.4 5.5] Original dtype: float64 Converted array: [1 2 3 4 5] Converted dtype: int32

Example: In-place Type Conversion

import numpy as np e = np.array([1, 2, 3, 4, 5], dtype=np.float32) print("Array:", e) print("Data type:", e.dtype)

Output:

Array: [1. 2. 3. 4. 5.] Data type: float32

What if a Value Cannot Be Converted?

When converting data types, you may encounter values that cannot be converted. Let us explore different scenarios.

Scenario 1: Converting Non-numeric Strings to Numbers

import numpy as np a = np.array(['1', '2', 'three', '4', '5']) try: a_int = a.astype(np.int32) except ValueError as e: print("Error:", e)

Output:

Error: invalid literal for int() with base 10: 'three'

Scenario 2: Converting Out-of-Range Numbers

import numpy as np b = np.array([1.1e10, 2.2e10, 3.3e10]) try: b_int = b.astype(np.int32) except OverflowError as e: print("Error:", e)

Output:

Error: OverflowError: (34, 'Numerical result out of range')

Scenario 3: Converting Complex Numbers to Real Numbers

import numpy as np c = np.array([1+2j, 3+4j, 5+6j]) c_float = c.astype(np.float32) print("Converted array:", c_float)

Output:

ComplexWarning: Casting complex values to real discards the imaginary part Converted array: [1. 3. 5.]

Scenario 4: Handling Conversion Errors

import numpy as np d = np.array(['1', '2', 'three', '4', '5']) def safe_convert(arr, target_type): try: return arr.astype(target_type) except ValueError as e: print("Conversion error:", e) return None d_int = safe_convert(d, np.int32)

Output:

Conversion error: invalid literal for int() with base 10: 'three'

Scenario 5: Using "np.nan" for Invalid Conversions

import numpy as np e = np.array(['1.1', '2.2', 'three', '4.4', '5.5']) def convert_with_nan(arr): result = [] for item in arr: try: result.append(float(item)) except ValueError: result.append(np.nan) return np.array(result) e_float = convert_with_nan(e) print("Converted array:", e_float)

Output:

Converted array: [1.1 2.2 nan 4.4 5.5]

Converting Data Type on Existing Arrays

You can also convert the data type of existing arrays using the view() method to change the interpretation of the data without changing the underlying bytes.

Example

import numpy as np g = np.array([1, 2, 3, 4], dtype=np.int32) g_view = g.view(np.float32) print("Viewed array:", g_view)

Output:

Viewed array: [1.4012985e-45 2.8025969e-45 4.2038954e-45 5.6051939e-45]