← Back to NumPy Course | Chapter 12: Advanced Topics | Lesson 1 of 7

Structured arrays

A structured array works like a tiny table: each element has named fields of possibly different types.

In this page:

  1. Structured arrays
Syntax
python
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

python
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
  1. Forgetting string fields need a fixed size like U10
  2. Mixing up field access with indexing
  3. 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:

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.