Structured arrays
A structured array works like a tiny table: each element has named fields of possibly different types.
In this page:
Syntax
dt = np.dtype([("field1", type1), ("field2", type2)])
arr = np.array([(value1, value2)], dtype=dt)
arr["field1"]
Structured arrays
Define a compound dtype as a list of (name, type) pairs. Each field is accessed by name, and the array stays fast and compact. Structured arrays suit small heterogeneous records; for large tabular work use Pandas.
Note:
Use np.sort with order="field" to sort records by a field.
Example: Structured arrays
import numpy as np
people = np.array(
[("Ann", 31, 55.5), ("Bob", 25, 70.2)],
dtype=[("name", "U10"), ("age", "i4"), ("weight", "f4")],
)
print(people["name"])
print(people[1])
print(np.sort(people, order="age")["name"])
# Output:
# ['Ann' 'Bob']
# ('Bob', 25, 70.2)
# ['Bob' 'Ann']
Related Topics
Common Mistakes
- Forgetting string fields need a fixed size like U10
- Mixing up field access with indexing
- Reaching for structured arrays when Pandas is a better fit
Chapter Summary
- dtype is a list of (name, type) pairs
- Access fields by name
- Each record can mix types
- Sort with order
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: