Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy dtype: Data Types, astype and Structured Dtypes

How to read, set and convert a NumPy dtype: astype and its casting rules, structured dtypes for instrument tables, and how to catch silent integer overflow.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

A NumPy dtype (data type object) describes how the bytes in each fixed-size item of an array are interpreted: the kind of value (integer, float, string, Python object), its size in bytes, its byte order and, for structured data, its named fields. You read it with arr.dtype, set it with the dtype= argument when you create an array, and change it by calling arr.astype(...), which returns a converted copy.

What a NumPy dtype is used for in research

Research data arrive as instrument exports, survey tables and simulation output, and the same numbers can be stored in very different ways. Counts fit in a 32-bit integer, readings usually need a 64-bit float, and sensor labels are fixed-width strings. The dtype is where that decision lives. It controls memory use, whether a calculation can overflow, how an array is written to disk and read back, and whether a column of labels can be mixed with numbers at all. Choosing and checking dtypes deliberately is a small step that prevents silent errors in downstream statistics, in particular the integer overflow described in the troubleshooting section below.

The NumPy documentation describes a dtype as an instance of the numpy.dtype class that records the type of the data (integer, float or Python object), the size of the data in bytes, the byte order, the names and types of the fields when the type is structured, and the shape and data type when the item is a sub-array. Scalar types such as np.float64 are not dtype objects, although they can be used anywhere a dtype is needed, and indexing a single element of an array returns a scalar type object. If you work with tabular data in a data frame instead, the same ideas apply column by column; see the pandas dtypes guide.

The five basic numeric kinds

The NumPy user guide groups the basic numeric types into five kinds: bool, int, uint, float and complex. A concrete type name is the kind plus its bit size, for example int32 or float64. Python’s own types map onto NumPy types as follows: a Python int becomes numpy.int_, bool becomes numpy.bool, float becomes numpy.float64 and complex becomes numpy.complex128. The sizes of numpy.int_ and numpy.intp depend on the platform, which matters when arrays are passed to C or Fortran code. Text is stored as fixed-width numpy.str_ (code U), numpy.bytes_ (S) or numpy.void (V).

How to install or access it

NumPy is installed from the official project page at numpy.org/install. The page gives pip install numpy for pip, and for conda it shows creating and activating an environment and then running conda install numpy. Its verification step is:

import numpy as np
print(np.__version__)

The examples below were run with NumPy 2.5.4 on Linux. The casting="same_value" option used in the overflow check was added to ndarray.astype in NumPy 2.4, so it needs 2.4 or newer; every other call here works on older releases.

Step-by-step: inspect, set and convert a dtype

Step 1. Read the dtype of an existing array

Every array has a dtype attribute. The user guide shows the pattern:

import numpy as np
z = np.arange(3, dtype=np.uint8)
z
# array([0, 1, 2], dtype=uint8)
z.dtype
# dtype('uint8')

A dtype object also exposes attributes you can query. In the reference page, dt = np.dtype('>i4') gives dt.byteorder of '>' (big-endian), dt.itemsize of 4 (bytes), dt.name of 'int32', and dt.type is np.int32 evaluates to True. The reference lists these attributes: kind, char, num, str, name, itemsize, byteorder, fields, names, subdtype, shape, hasobject, flags, isbuiltin, isnative, descr, alignment, base and metadata.

Step 2. Choose the dtype when you create the array

Pass dtype= as a type object, a string or a one-letter character code. The user guide notes that np.array([1, 2, 3], dtype='f') gives float32 and dtype='d' gives float64. Calling np.dtype(None) returns the default data type, float64. Instruments that deliver data in a fixed byte order can be described with the '>' and '<' prefixes, as in '>i4' above. The dataset below lists the spellings used in this guide next to the dtype each resolves to.

Step 3. Convert with astype

The signature in the reference is ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True), and it returns a copy of the array cast to the specified type. The parameters are:

  • dtype: a typecode or data type to cast to. This is the only required argument.
  • order: memory layout of the result, one of 'C', 'F', 'A' or 'K'; the default 'K' keeps the layout as close to the original as possible.
  • casting: what kind of casting is allowed. Options are 'no', 'equiv' (byte-order changes only), 'safe' (only casts that preserve values), 'same_kind' (safe casts or casts within a kind, such as float64 to float32), 'unsafe' (any conversion) and 'same_value' (any conversion, provided values do not change, including through float rounding or integer overflow). The default is 'unsafe' for backwards compatibility.
  • subok: if True (the default), subclasses pass through; if False the result is a base-class array.
  • copy: by default a new array is always returned. With copy=False the input array is returned only when the dtype, order and subok requirements are already satisfied.

The documentation example shows why the casting choice matters for data you care about:

x = np.array([1, 2, 2.5])
x.astype(np.int_)
# array([1, 2, 2])
x.astype(np.int_, casting="same_value")
# ValueError: could not cast 'same_value' double to long
x[:2].astype(np.int_, casting="same_value")
# array([1, 2])

The first cast silently truncates 2.5 to 2 under the default 'unsafe' rule. The 'same_value' cast refuses, and slicing to the first two values, which convert exactly, succeeds.

Step 4. Test a dtype family instead of an exact type

np.issubdtype answers whether a dtype belongs to a family. From the user guide, np.issubdtype(np.dtype(np.int64), np.integer) is True and the same call against np.floating is False. This is more robust than comparing against one exact type when a function should accept any integer width.

A worked example: an instrument table as a structured dtype

This is an illustrative example built for this guide, not data from a real instrument. A structured dtype is a dtype made of named fields, each with its own type, so one array can hold a sensor label, an integer count, a floating-point reading and a flag. The structured-arrays page gives the form dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')]; the same pattern for a sensor log is:

dt = np.dtype([('sensor_id', 'U8'), ('count', 'i4'),
               ('reading', 'f8'), ('flag', '?')])
x = np.array([('S-01', 12, 0.4821, False),
              ('S-02', 7, 1.9035, True)], dtype=dt)
x
# array([('S-01', 12, 0.4821, False), ('S-02',  7, 1.9035,  True)],
#       dtype=[('sensor_id', '<U8'), ('count', '<i4'),
#              ('reading', '<f8'), ('flag', '?')])
x['reading']
# array([0.4821, 1.9035])
dt.names
# ('sensor_id', 'count', 'reading', 'flag')
dt.itemsize
# 45

Indexing by field name returns a view, so assigning to it modifies the original array. In the documentation, x['age'] = 5 sets every age in place. Indexing with an integer returns a mutable structured scalar of type numpy.void. Assignment between structured arrays is by position, not by field name, and the field counts must match. Use a tuple, not a list, when assigning a whole record, because a list triggers broadcasting.

The NumPy documentation itself points to pandas or xarray for general tabular analysis and presents structured arrays mainly for interfacing with C code and for interpreting binary data. Use a structured dtype when you need a fixed binary layout; use a data frame when you mainly filter, group and summarise.

Output and how to read it

The dtype string in an array printout is the dtype itself. Read '<f8' as: little-endian (<), kind float (f), 8 bytes per item, which is float64. '<U16' is a little-endian Unicode string of up to 16 characters, and '<i4' is a little-endian 32-bit integer. For a structured field, dt['grades'] on the documentation’s example returns dtype(('<f8', (2,))), meaning the field holds a sub-array of two float64 values. Printouts hide the dtype when it is the platform default for the values shown, so check arr.dtype directly rather than inferring it from how the numbers look.

Two attributes are worth checking when you validate a data pipeline. dt.itemsize is the number of bytes per element, which with the length of the array gives the memory the data occupy. dt.kind is a single character for the general kind of type, which is useful for a check such as “every column is numeric” before running statistics. For a numeric reduction such as a total, the result dtype also follows the input dtype; see NumPy sum for the accumulator behaviour.

Reading overflow results

Casting to a narrower integer follows C casting rules. The user guide shows an int64 value of 300 converted to int8 and giving 44, which is 300 minus 256. Run on a small series in NumPy 2.5.4:

a = np.array([300, -5, 12], dtype=np.int64)
a.astype(np.int8)
# array([44, -5, 12], dtype=int8)
a.astype(np.int8, casting='same_value')
# ValueError: could not cast 'same_value' long to byte

No warning accompanies the first result, so a column of counts that exceeds the target range turns into wrong but plausible numbers. When a conversion is meant to be lossless, use casting='same_value' (NumPy 2.4 or newer) or compare the converted array with the original before using it.

Troubleshooting

Symptom Cause What to do
Integers change value after astype to a smaller type Casting follows C rules, so 300 as int8 becomes 44 Choose a wider type, or cast with casting='same_value' so overflow raises ValueError
Floats become integers with the decimals dropped The default casting='unsafe' allows any conversion; 2.5 became 2 in the documentation example Round first with the approach in NumPy round, or use 'same_value' to make the cast fail
ValueError: could not convert string to float A string element is not a number, as seen when casting an array of text to float Clean or mask the offending values before converting
ComplexWarning on cast Casting from complex to float or int discards the imaginary part Use a.real.astype(t), as the reference advises
Assigning a list to a structured element behaves unexpectedly Lists trigger broadcasting Assign a tuple, for example x[1] = (7, 8, 9)
Code that viewed a multi-field selection as one packed type breaks Since NumPy 1.16 a multi-field view keeps the original itemsize and offsets, including padding Use numpy.lib.recfunctions.repack_fields to restore a packed layout
Integer size differs between machines numpy.int_ and numpy.intp vary with platform bit size Name the size explicitly, for example np.int64, when you exchange data with C or Fortran code
You expected a copy-free conversion but memory doubled astype returns a new array by default Pass copy=False only when dtype, order and subok already match; otherwise a copy is unavoidable

When you build arrays from existing lists or files, NumPy asarray converts input to an array without copying when it is already an array of the right type, and NumPy linspace accepts a dtype argument for the output of a generated grid.

NumPy dtypes are not the only way to describe typed columns. All three options below are free and open source. The first two are in NumPy; the third is named by the NumPy structured-arrays page as the choice for tabular analysis.

Option What it gives you Source statement
Structured dtype (np.dtype([...])) Named fields with individual types and byte offsets in one ndarray Structured-arrays page: fields mimic C structs and suit interfacing with C code
Record array (np.recarray) The same layout with attribute access, so recordarr.bar works like recordarr['bar'] Structured-arrays page, record arrays section
pandas or xarray Labelled columns or dimensions for tabular and multi-dimensional analysis Structured-arrays page recommends them for tabular analysis; see the pandas dtypes guide

FAQ

How do I check the dtype of a NumPy array?

Read the dtype attribute, as in z.dtype, which returns for example dtype('uint8'). Attributes such as itemsize, kind and byteorder on the dtype object give the size in bytes, the general kind and the byte order. To test a whole family instead of one exact type, use np.issubdtype.

Does astype make a copy of the array?

Yes by default. ndarray.astype has copy=True, so a new array is always returned. With copy=False the input array is returned only when the dtype, order and subok requirements are already satisfied.

How do I avoid silent integer overflow when converting to a smaller type?

Casting follows C rules, so an int64 value of 300 cast to int8 becomes 44 without a warning. Choose a wider type, or pass casting='same_value' (NumPy 2.4 or newer) so that a conversion that would change a value raises ValueError.

What is a structured dtype?

A structured dtype is made of named fields, each with its own type, so one array can hold a text label, an integer count and a float reading together, for example dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')]. The NumPy documentation presents it mainly for interfacing with C code and interpreting binary data, and recommends pandas or xarray for general tabular analysis.

Sources

  • NumPy documentation, Data type objects (numpy.dtype): https://numpy.org/doc/stable/reference/arrays.dtypes.html (read 2026-11-14)
  • NumPy user guide, Data types: https://numpy.org/doc/stable/user/basics.types.html (read 2026-11-14)
  • NumPy reference, numpy.ndarray.astype: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html (read 2026-11-14)
  • NumPy user guide, Structured arrays: https://numpy.org/doc/stable/user/basics.rec.html (read 2026-11-14)
  • NumPy, Installing NumPy: https://numpy.org/install/ (read 2026-11-14)

Data: NumPy dtype spellings and what they resolve to

Each spelling that a NumPy user can pass as dtype= was evaluated with np.dtype() in NumPy 2.5.4 and its resolved name, itemsize in bytes, kind code and byte order recorded. The spellings and attributes are those documented in the NumPy data type objects reference and data types user guide.

NumPy dtype spellings and what they resolve to
dtype spellingResolved dtypeItemsize (bytes)Kind codeByte order
f8float648f=
f4float324f=
i4int324i=
>i4int324i>
u1uint81u|
dfloat648f=
ffloat324f=
U1664U=

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about NumPy dtype: Data Types, astype and Structured Dtypes

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →