NumPy: Structured Arrays
Last updated: 2026-08-26
1. What You'll Learn
- ❶ Creating structured arrays with multiple dtypes
- ❷ Accessing fields by name
- ❸ Record arrays for attribute-style access
- ❹ Sorting and filtering structured arrays
2. Key Concepts
PYTHON
import numpy as np
# Define structured dtype
dt = np.dtype([('name', 'U10'), ('age', 'i4'), ('salary', 'f8')])
# Create array
employees = np.array([
('Alice', 30, 75000.0),
('Bob', 25, 62000.0),
('Charlie', 35, 85000.0),
('Diana', 28, 71000.0)
], dtype=dt)
# Access fields
print(employees['name']) # ['Alice' 'Bob' 'Charlie' 'Diana']
print(employees['salary']) # [75000. 62000. 85000. 71000.]
# Record array (attribute access)
emp_rec = np.rec.array(employees)
print(emp_rec.name) # ['Alice' 'Bob' 'Charlie' 'Diana']
print(emp_rec.salary) # [75000. 62000. 85000. 71000.]
# Filtering
print(employees[employees['salary'] > 70000]['name'])
# ['Alice' 'Charlie']
# Sorting
sorted_emp = np.sort(employees, order='salary')
print(sorted_emp['name']) # ['Bob' 'Diana' 'Alice' 'Charlie']
TEXT
📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example: Creating and accessing structured arrays (Difficulty ⭐)
PYTHON
import numpy as np
dt = np.dtype([('product', 'U15'), ('price', 'f8'), ('quantity', 'i4')])
inventory = np.array([
('Widget', 9.99, 100),
('Gadget', 24.99, 50),
('Doohickey', 4.99, 200),
('Thingamajig', 14.99, 75)
], dtype=dt)
print("Products:", inventory['product'])
print("Prices:", inventory['price'])
print("Total value:", np.sum(inventory['price'] * inventory['quantity']))
Output:
TEXT 📖 Display onlyProducts: ['Widget' 'Gadget' 'Doohickey' 'Thingamajig'] Prices: [ 9.99 24.99 4.99 14.99] Total value: 4396.0
▶ Example: Filtering structured arrays (Difficulty ⭐⭐)
PYTHON
import numpy as np
dt = np.dtype([('name', 'U15'), ('age', 'i4'), ('salary', 'f8')])
employees = np.array([
('Alice', 30, 75000), ('Bob', 25, 62000),
('Charlie', 35, 85000), ('Diana', 28, 71000),
('Eve', 45, 95000), ('Frank', 32, 78000)
], dtype=dt)
# Filter: salary > 70000 AND age < 40
mask = (employees['salary'] > 70000) & (employees['age'] < 40)
filtered = employees[mask]
print("Filtered:", filtered['name'])
# Average salary by age group
young = employees[employees['age'] < 30]
print("Young avg salary:", young['salary'].mean())
Output:
TEXT 📖 Display onlyFiltered: ['Alice' 'Charlie' 'Frank'] Young avg salary: 66500.0
▶ Example: Sorting structured arrays by field (Difficulty ⭐⭐)
PYTHON
import numpy as np
dt = np.dtype([('city', 'U15'), ('population', 'i4'), ('area', 'f8')])
cities = np.array([
('Tokyo', 13960000, 2194), ('Delhi', 16780000, 1484),
('Shanghai', 24870000, 6341), ('Mumbai', 12440000, 603),
('Beijing', 21540000, 16411)
], dtype=dt)
# Sort by population descending
by_pop = np.sort(cities, order='population')[::-1]
print("By population:", by_pop['city'])
# Sort by density (population / area)
density = cities['population'] / cities['area']
dense_idx = np.argsort(-density)
print("By density:", cities['city'][dense_idx])
Output:
TEXT 📖 Display onlyBy population: ['Shanghai' 'Beijing' 'Delhi' 'Tokyo' 'Mumbai'] By density: ['Mumbai' 'Delhi' 'Tokyo' 'Shanghai' 'Beijing']
Q When should I use structured arrays vs Pandas?
A Use structured arrays when you need NumPy's speed and memory efficiency for homogeneous operations. Use Pandas for more complex data analysis with labeling, grouping, and missing data handling.
Q Can I add fields to an existing structured array?
A No — structured arrays have a fixed dtype. Create a new dtype with the additional fields and copy data over. Use
np.lib.recfunctions.append_fields for convenience.Q What's the difference between structured array and recarray?
A recarray (record array) allows attribute access (
emp.name) in addition to field access (emp['name']). It's slightly slower but more convenient.❓ FAQ
Q What is the most important thing to remember?
A NumPy operations are vectorized — avoid Python loops for better performance.
Q Where can I learn more?
A Check the official NumPy documentation at numpy.org for detailed references and advanced topics.
Q Does this work with NumPy 2.x?
A Yes — all examples are compatible with NumPy 2.x. Some older APIs (like np.random.seed) are still supported but the modern alternatives are recommended.
📖 Summary
- Structured arrays store mixed types in a single ndarray using compound dtypes
- Access fields by name:
arr['fieldname'] - Record arrays enable attribute-style access:
arr.fieldname - Filter and sort by field values using boolean masks and
np.sort - For complex tabular data, consider Pandas DataFrames
📝 Exercises
-
Beginner (Difficulty ⭐): Create a structured array with fields: product (U20), price (f8), quantity (i4). Add 5 products.
-
Intermediate (Difficulty ⭐⭐): From the products array, filter items with price > 50 and quantity < 10. Sort by price descending.
-
Advanced (Difficulty ⭐⭐⭐): Use
np.lib.recfunctionsto append a 'total_value' field (price × quantity) to the array. Verify the calculation.