← Back to NumPy Course | Chapter 1: Getting Started | Lesson 6 of 7

dtype basics

Every array remembers what kind of numbers it holds (whole numbers, decimals and so on) and that choice affects memory and precision.

In this page:

  1. dtype basics
Syntax
python
arr = np.array([value1, value2], dtype=np.float64)
arr.dtype
arr.astype(np.int32)

dtype basics

The dtype describes the type of every element, such as int64, float64, bool or complex128. NumPy infers it from your data, but you can set it with the dtype argument or convert later with astype. Mixing ints and floats upcasts everything to float.

Note: Use smaller dtypes such as int8 or float32 to save memory on large arrays.

Example: dtype basics

python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([1, 2.5, 3])
c = np.array([1, 2, 3], dtype=np.float32)

print(a.dtype, b.dtype, c.dtype)
print("astype int:", b.astype(int))

# Output:
# int64 float64 float32
# astype int: [1 2 3]
Related Topics
Common Mistakes
  1. Assuming ints stay ints after mixing with floats
  2. Overflowing small integer types silently
  3. Forgetting astype returns a new array
Chapter Summary
  • dtype sets the element type
  • NumPy infers dtype but you can override it
  • astype converts to a new dtype
  • Mixed int and float becomes float
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.