Structured Arrays
Normal NumPy arrays hold one type. But real records often mix types: a product has a name (text), a price (float) and a stock count (integer). A structured array gives each element a set of named fields, each with its own dtype, a bit like a row in a database table or a C struct.
Defining a structured dtype
A structured dtype is a list of (name, type) pairs. Each element of the array is then one record:
import numpy as np
product_t = np.dtype([("name", "U10"), ("price", "f8"), ("stock", "i4")])
products = np.array([
("pencil", 0.80, 120),
("notebook", 3.50, 40),
("stapler", 7.25, 8),
("eraser", 0.60, 0),
], dtype=product_t)
print(products)
print(products.dtype)
print(products.shape, products.itemsize, "bytes per record")[('pencil', 0.8 , 120) ('notebook', 3.5 , 40) ('stapler', 7.25, 8)
('eraser', 0.6 , 0)]
[('name', '<U10'), ('price', '<f8'), ('stock', '<i4')]
(4,) 52 bytes per record
The type codes are the ones from the Data Types lesson: U10 is a string of up to 10 characters, f8 an 8-byte float, i4 a 4-byte integer. Each record takes 40 + 8 + 4 = 52 bytes.
Accessing fields and records
Index with a field name to get a whole column as a normal array; index with a position to get one record:
import numpy as np
product_t = np.dtype([("name", "U10"), ("price", "f8"), ("stock", "i4")])
products = np.array([("pencil", 0.80, 120), ("notebook", 3.50, 40),
("stapler", 7.25, 8), ("eraser", 0.60, 0)], dtype=product_t)
print(products["name"])
print(products["price"] * products["stock"]) # stock value per product
print(products[1]) # one record
print(products[1]["name"], products[1]["price"])
print(products[["name", "stock"]][:2]) # several fields['pencil' 'notebook' 'stapler' 'eraser']
[ 96. 140. 58. 0.]
('notebook', 3.5, 40)
notebook 3.5
[('pencil', 120) ('notebook', 40)]
Field arrays are views, so assigning to them changes the records:
import numpy as np
product_t = np.dtype([("name", "U10"), ("price", "f8"), ("stock", "i4")])
products = np.array([("pencil", 0.80, 120), ("notebook", 3.50, 40),
("stapler", 7.25, 8), ("eraser", 0.60, 0)], dtype=product_t)
products["price"] *= 1.10 # 10 % price increase
products["stock"][products["name"] == "eraser"] = 50
print(products)[('pencil', 0.88 , 120) ('notebook', 3.85 , 40) ('stapler', 7.975, 8)
('eraser', 0.66 , 50)]
Filtering and sorting records
Everything you learned about boolean masks and sorting works on whole records. np.sort can even sort by a field with order=:
import numpy as np
product_t = np.dtype([("name", "U10"), ("price", "f8"), ("stock", "i4")])
products = np.array([("pencil", 0.80, 120), ("notebook", 3.50, 40),
("stapler", 7.25, 8), ("eraser", 0.60, 0)], dtype=product_t)
low_stock = products[products["stock"] < 10]
print("reorder:", low_stock["name"])
by_price = np.sort(products, order="price")
print(by_price["name"])
print("most expensive:", products[products["price"].argmax()]["name"])reorder: ['stapler' 'eraser']
['eraser' 'pencil' 'notebook' 'stapler']
most expensive: stapler
Record arrays: attribute access
np.rec.array wraps a structured array so fields can be read as attributes (r.price instead of r["price"]):
import numpy as np
r = np.rec.array([("Oslo", 709_000, 454.0), ("Bergen", 291_000, 465.0)],
dtype=[("city", "U10"), ("pop", "i4"), ("area", "f8")])
print(r.city)
print((r.pop / r.area).round(1), "people per km2")['Oslo' 'Bergen']
[1561.7 625.8] people per km2
When to use them
Structured arrays are great for reading binary file formats, fixed-layout records and interfacing with C code, and they keep memory compact. For everyday tabular analysis, though, pandas DataFrames are usually more convenient: they have labelled columns of different types, missing-value handling, group-by and much more. A DataFrame can be created directly from a structured array with pd.DataFrame(products).
| Need | Use |
|---|---|
| Homogeneous numbers, maths | plain ndarray |
| Fixed-layout mixed records, binary data | structured array |
| Data analysis on tables | pandas DataFrame |
Test yourself
Given a structured array people with a field 'age', how do you get all ages?
- people.age()
- people['age']
- people[age]
- people.get('age')
What does the dtype code U8 mean?
- An 8-byte unsigned integer
- A Unicode string of up to 8 characters
- An 8-bit float
- 8 Unicode fields
How can you sort a structured array by its 'price' field?
- np.sort(a, key='price')
- np.sort(a, order='price')
- a.sort_by('price')
- np.argsort(a, 'price')