Data Types
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Every NumPy array stores elements of a single data type, its dtype. The dtype fixes how many bytes an element uses, how those bytes are interpreted, and what happens when numbers get too large. Choosing it well halves memory use, makes file formats portable, and prevents silent wrap-around; choosing it carelessly produces some of the hardest bugs in numerical code.
This page targets NumPy 2.5 (2.5.4 was current in October 2026). Examples target Python 3.13 or 3.14 and were run on Python 3.13. All examples were executed with NumPy 2.5.4 on a 64-bit macOS machine; where a result depends on the platform it is said so. What happens when two dtypes meet in one operation is the subject of Type Promotion. Text and structured types are covered in Strings, Bytes & StringDType and Structured Arrays, dates in Dates & Times, and the Python-level number types in Python numbers.
Array scalars and dtype objects
Two kinds of objects describe types. A dtype object (np.dtype) describes the layout of one element. An array scalar
(np.int32, np.float64, …) is the Python type of a single element extracted from an array. Both can be used wherever a
dtype is expected.
import numpy as np
print(np.array([1, 2, 3]).dtype, np.array([1., 2]).dtype, np.array([True]).dtype,
np.array([1 + 2j]).dtype, np.array(["a", "bcd"]).dtype)
print(np.dtype("int32"), np.dtype("<i4"), np.dtype(np.int32) == np.int32, np.dtype("f8"),
np.dtype("U5"), np.dtype("M8[D]"))
print(np.float64(3.0), repr(np.float64(3.0)), str(np.float64(3.0)))
Output:
int64 float64 bool complex128 <U3 int32 int32 True float64 <U5 datetime64[D] 3.0 np.float64(3.0) 3.0
The default integer is int64 on 64-bit Linux and macOS, and, since NumPy 2.0, also on 64-bit Windows, where it used to
be 32-bit. Code that relied on the Windows int32 default (overflowing, or matching a C long in an extension) must now
ask for the width it needs. The default float is float64 and the default complex is complex128.
Since NumPy 2.0 (NEP 51) the repr of a scalar includes its type, np.float64(3.0), while str and print still show
3.0. np.set_printoptions(legacy="1.25") restores the old representation, which matters when comparing the printed output
of old doctests.
The built-in types
| Kind | Names (type codes) | Notes |
|---|---|---|
Boolean |
|
One byte per element. |
Signed integer |
|
Two’s complement |
Unsigned integer |
|
Wraps modulo 2n |
Floating point |
|
IEEE 754 half, single and double |
Complex |
|
A pair of |
Extended |
|
Platform dependent; 64 bits on this arm64 Mac, 80-bit extended on x86 Linux |
Text |
|
See the strings page |
Time |
|
Units such as |
Generic |
|
Python references; structured records |
A numeric type code is <kind><bytes>, so f8 is a float of 8 bytes. Kind letters are b (bool), i, u, f, c, U,
S, M, m, O and V. The code is available on the dtype as .char and .kind, the width in bytes as .itemsize,
and the canonical name as .name.
d = np.dtype("f8")
print(d.kind, d.char, d.itemsize, d.name, np.dtype("i2").str)
print(np.zeros(3, dtype=np.float32).nbytes, np.zeros(3).itemsize)
Output:
f d 8 float64 <i2 12 8
Platform-dependent names
C-like names follow the platform, so they are risky in portable code:
-
np.intpandnp.uintpare pointer-sized integers, the right type for indices. On a 64-bit platform they areint64anduint64. -
np.intcis the Cint(int32here).np.longandnp.ulongfollow the Clong(32-bit on Windows), and the default integer no longer followslongsince NumPy 2.0. -
np.longdoubleis the Clong double: 64 bits on Apple silicon and Windows, 80 bits stored in 128 on x86 Linux. Do not count on extra precision.
print(np.dtype(np.intp), np.dtype(np.uintp), np.dtype(np.intc), np.dtype(np.long))
print(np.bool is np.bool_, np.dtype(np.bool).itemsize)
Output:
int64 uint64 int32 int64 True 1
Limits: iinfo and finfo
np.iinfo reports the range of an integer type and np.finfo the characteristics of a float type.
for t in (np.int8, np.uint8, np.int16, np.int32, np.int64):
i = np.iinfo(t)
print(t.__name__, i.min, i.max, i.bits)
for t in (np.float16, np.float32, np.float64):
f = np.finfo(t)
print(t.__name__, f.bits, f.eps, f.max, f.precision)
Output:
int8 -128 127 8 uint8 0 255 8 int16 -32768 32767 16 int32 -2147483648 2147483647 32 int64 -9223372036854775808 9223372036854775807 64 float16 16 0.000977 6.55e+04 3 float32 32 1.1920929e-07 3.4028235e+38 6 float64 64 2.220446049250313e-16 1.7976931348623157e+308 15
eps is the gap between 1.0 and the next representable number, so float32 carries about 7 significant decimal digits and
float64 about 16. That is why the constant np.float32(0.1) and the Python float 0.1 are different numbers, and why
np.float32(16777216) + np.float32(1) is still 16777216.0.
Overflow
Fixed-width integers wrap around instead of growing. NumPy’s behaviour differs between array operations and scalar operations.
import warnings
a = np.array([250, 5], dtype=np.uint8)
print(a + np.uint8(10)) # array arithmetic wraps silently
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
print(np.uint8(250) + np.uint8(10)) # scalar arithmetic wraps and warns
print([str(x.message) for x in w])
Output:
[ 4 15] 4 ['overflow encountered in scalar add']
NumPy does not warn when an array operation overflows, because checking every element would slow every operation. Guard
your inputs: pick a wider dtype (np.int64, or a float) for sums and products, use np.iinfo to test the range, or
accumulate with dtype=, for example a.sum(dtype=np.int64). A Python integer that cannot fit the array’s dtype is
rejected rather than wrapped:
try:
np.array([300], dtype=np.uint8)
except OverflowError as e:
print(e)
print(np.array([300]).astype(np.uint8)) # astype wraps instead of raising
Output:
Python integer 300 out of bounds for uint8 [44]
Floating-point overflow gives inf, not wrap-around: np.float16(65504) + np.float16(100) is inf. How these cases are
reported or turned into exceptions is configured with np.errstate; see
Floating-Point Errors & errstate.
Converting with astype
arr.astype(dtype) returns a new array of another type. By default it always copies, even when the dtype is unchanged; pass
copy=False to reuse the array when no conversion is needed.
x = np.arange(3, dtype=np.int32)
y = x.astype(np.float64)
print(y.dtype)
print(x.astype(np.int32, copy=False) is x)
f = np.array([1.7, -1.7, np.nan, 1e20])
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
print(f.astype(np.int64))
print([str(m.message) for m in w])
print(np.array([1.7, -1.7]).astype(int), np.round([1.5, 2.5, -0.5]), np.trunc(-1.7))
Output:
float64 True [ 1 -1 0 9223372036854775807] ['invalid value encountered in cast'] [ 1 -1] [ 2. 2. -0.] -1.0
Float to integer conversion truncates toward zero, it does not round, and nan or out-of-range values produce
platform-dependent integers with a RuntimeWarning. np.round rounds halves to the nearest even number (2.5 becomes
2.0). Since NumPy 2.4 np.round always returns a copy.
Casting rules
The casting= argument of astype, ufuncs and concatenate limits which conversions are allowed:
| Rule | Allows |
|---|---|
|
No conversion at all |
|
Only byte-order changes |
|
Conversions that cannot lose information, such as |
|
Safe casts, plus within a kind, such as |
|
Any conversion (the default for |
|
Any conversion, but raises if a value changes (new in NumPy 2.4) |
try:
np.array([1.5]).astype(np.int32, casting="safe")
except TypeError as e:
print(e)
print(np.can_cast(np.int32, np.float64), np.can_cast(np.int64, np.float64),
np.can_cast(np.float64, np.float32, "same_kind"))
try:
np.array([1.5, 2.5]).astype(np.int32, casting="same_value")
except ValueError as e:
print(e)
print(np.array([1.0, 2.0]).astype(np.int32, casting="same_value"))
Output:
Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'safe'
True True True
could not cast 'same_value' double to int
[1 2]
casting="same_value" is the safest way to convert measurements to a compact integer type: it succeeds only if every value
survives the round trip. Note that can_cast(int64, float64) is True although some large integers cannot be represented
exactly; the "safe" rule follows the type hierarchy, not individual values. np.issubdtype(np.int32, np.integer) tests
membership in an abstract family.
Reinterpreting bytes with view
arr.view(dtype) reinterprets the same memory as another dtype, with no conversion, which is useful for inspecting bit
patterns and fatal for numerical work if confused with astype.
print(np.arange(4, dtype=np.int32).view(np.uint32).dtype)
print(np.array([1.0], dtype=np.float32).view(np.int32))
Output:
uint32 [1065353216]
Assigning to arr.dtype to reinterpret an array is deprecated in NumPy 2.5; use view.
Byte order
A dtype records the byte order: < little-endian, > big-endian, = native and | not applicable. Files written by
big-endian systems are read correctly when you give the dtype with its byte order, and astype converts the values.
print(np.dtype(">i4"), np.dtype(">i4").byteorder, np.array([1], dtype=">i4").astype("<i4").dtype)
Output:
>i4 > int32
The object dtype
dtype=object stores Python references. It allows mixed content and integers of any size, but disables vectorised speed and
most compact storage.
print(np.array([1, 2, 3], dtype=object).dtype)
print(np.array([2**70]).dtype)
Output:
object object
A Python integer too large for int64 makes NumPy fall back to object silently, so a column of identifiers that
suddenly becomes object is usually a sign of out-of-range values.
Choosing a dtype
-
Counts, indices, labels: a signed integer.
intpfor indices;int32or smaller only when memory demands it. -
Pixels and bytes:
uint8(and widen before arithmetic). -
Measurements:
float64. Usefloat32for large arrays and machine learning where 7 digits suffice, andfloat16only for storage. -
Flags and masks:
bool. -
Money: not
float; use integers of the smallest currency unit or thedecimalmodule. -
Text:
StringDTypefor variable-length strings, as described in the strings page.
Aliases and names removed in NumPy 2.0
Older books and tutorials use names that no longer exist. In NumPy 2.0 these were removed from the main namespace (the
list is not complete; Ruff rule NPY201 reports and fixes many of them):
| Old name | Use instead |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
the private |
np.bool was also reintroduced as the canonical bool name, replacing the old habit of writing np.bool_ or the builtin
bool. The full list is in the NumPy 2 migration guide and Migrating to NumPy 2.x.
Common pitfalls
-
Silent wrap-around in integer arrays, especially
uint8images; widen before arithmetic. -
astypeto integer truncates, it does not round, and invalid casts only warn. -
astypecopies by default; for large arrays passcopy=Falsewhen the dtype may already match. -
Platform differences in
long,longdoubleand (before 2.0) the default integer on Windows. -
viewversusastype: the first reinterprets bytes, the second converts values. -
Python scalars adopt the array dtype under NEP 50, so
arr_uint8 + 300raises rather than wrapping; see Type Promotion.
References
-
NumPy user guide, data types: https://numpy.org/doc/stable/user/basics.types.html
-
NumPy reference, data type objects: https://numpy.org/doc/stable/reference/arrays.dtypes.html
-
NumPy reference, scalars: https://numpy.org/doc/stable/reference/arrays.scalars.html
-
numpy.ndarray.astype: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html -
NEP 51, changing the representation of NumPy scalars: https://numpy.org/neps/nep-0051-scalar-representation.html
-
NumPy 2.0 migration guide: https://numpy.org/doc/stable/numpy_2_0_migration_guide.html