3. Numpy Data Objects, dtype
By Bernd Klein. Last modified: 07 May 2025.
dtype
Chapter: Data Type dtype in NumPy
NumPy, the fundamental package for numerical computing in Python, relies heavily on efficient storage and manipulation of data. At the heart of this efficiency is the concept of dtype—short for data type. Every NumPy array has a dtype that describes the type of elements it contains, such as integers, floating-point numbers, booleans, or even user-defined types.
Understanding dtype is critical not only for performance optimization but also for ensuring the correctness of computations. In this chapter, we explore how NumPy uses dtype to manage memory, how different data types behave, how to inspect and convert them, and how custom data types can be created for advanced use cases.
The data type object 'dtype' is an instance of numpy.dtype class. It can be created with numpy.dtype. We had already done this in the previous chapters of our Numpy tutorial:
import numpy as np
arr = np.array([1, 2, 3])
print(arr.dtype)
OUTPUT:
int64
We had also learned how to create arrays with a specific dtype. In the previous example, we let NumPy make the decision, and it chose int64. You are well advised to always create an array with a specific dtype to ensure consistency and portability. So the previous example should look like this:
arr = np.array([1, 2, 3], dtype=np.float32)
print(arr)
print(arr.dtype)
OUTPUT:
[1. 2. 3.] float32
So far, we have used in our examples of NumPy arrays only fundamental numeric data types like int and float. These NumPy arrays contained solely homogeneous data types. dtype objects, however, can also be constructed by combining fundamental data types.
With the aid of dtype, we are capable of creating Structured Arrays—also known as Record Arrays. Structured arrays provide us with the ability to have different data types for different columns within a single array. This structure resembles that of an Excel spreadsheet or a CSV file, where each column can hold a different type of data.
This makes it possible to define and manage complex data like the one in the following table using a custom dtype:
| Country | Population Density | Area | Population |
|---|---|---|---|
| Netherlands | 544 | 33720 | 18,346,819 |