Introduction to NumPy Lesson

Numpy Data Types

4 min to complete · By Gilad Gressel

Generally speaking, you won't have to worry about the NumPy data types, also known as NumPy datatypes and NumPy dtype, which we'll use interchangeably. However, it is good to know that they exist and that they are different from the datatypes in Python. In this lesson, you'll learn about the different NumPy data types and how to check the datatype of an array.

Categories of NumPy Data Types

The NumPy data types fall into five categories:

  1. Integer types: These are the same as the Python integer types, i.e., int8, int16, int32, int64, and int128. The default integer type in NumPy is int64.
  2. Floating point types: These are the same as the Python floating point types, i.e., float16, float32, float64, and float128. The default floating point type in NumPy is float64.
  3. Complex types: These are the same as the Python complex types, i.e. complex64 and complex128. The default complex type in NumPy is complex128.
  4. Unsigned integer types: These are the same as the Python unsigned integer types, i.e., uint8, uint16, uint32, uint64, and uint128.
  5. Boolean types: These are the same as the Python Boolean type, i.e., bool.

Under the hood, it's a bit more complicated, but most of the time, you can pretty much ignore the type of your array and just let NumPy decide. However, there are a few cases where you may need to dig around.

Checking the Data Type of an Array

In order to check the NumPy data type, you can use the dtype attribute of the array. For example:

import numpy as np
a = np.ones((3, 3))
print(a.dtype)
float64
a = np.ones((3, 3), dtype=np.int8)
print(a.dtype)
int8

Importantly, you cannot mix datatypes in an np.array because the entire point of NumPy is to have homogeneous (single type) arrays in fixed contiguous memory. It allows for the increased performance.

However, you may want to change the datatype to either:

  1. Save memory - this means you should select a lower precision datatype
  2. Increase precision - this means you should select a higher precision datatype

How to Change NumPy Data Types

In order to change datatypes, you can use the astype method of the array. For example:

a = a.astype(np.float64)
a.dtype
dtype('float64')
Colorful illustration of a light bulb

Note: Once you create an array with a dtype, the dtype is immutable. You cannot change the NumPy dtype in memory; you need to create a new array with the new dtype. This is not a problem at all, just something to be aware of.

Summary: NumPy Data Types

  • NumPy has many data types that are specific with varying degrees of precision (and memory consumption).
  • NumPy is designed to be ideal for both scientific computing and machine learning.
  • You generally do not need to think much about the NumPy dtype, but you will most likely need to be aware of it at certain points along your path.