Module 6 · Lesson 4

Structured Arrays

A structured array has a dtype made of named fields, so each element is a small fixed-layout record rather than a single number — useful for tabular data when you don’t want to bring in pandas. Define the dtype with a list of (field_name, field_dtype) pairs, then index a field by name like a dict key. np.sort(arr, order="field_name") sorts the whole array by one field.

dtype = np.dtype([("name", "U10"), ("age", "i4"), ("score", "f8")])
people = np.array(
    [("Ana", 34, 91.5), ("Boris", 29, 88.0), ("Chiko", 41, 95.25)],
    dtype=dtype,
)
print(people["name"])
print(people["score"])

by_age = np.sort(people, order="age")
print(by_age)

Output:

['Ana' 'Boris' 'Chiko']
[91.5  88.   95.25]
[('Boris', 29, 88.  ) ('Ana', 34, 91.5 ) ('Chiko', 41, 95.25)]
4.1

Build a structured array

Write make_people(names, ages, scores) that takes three equal-length sequences and returns a structured array with dtype [("name", "U10"), ("age", "i4"), ("score", "f8")], one record per input triple.

💡 Hint

Zip the three sequences into a list of tuples, then pass that list and the dtype straight to np.array(...).

✅ Solution
def make_people(names, ages, scores):
    dtype = np.dtype([("name", "U10"), ("age", "i4"), ("score", "f8")])
    records = list(zip(names, ages, scores))
    return np.array(records, dtype=dtype)
4.2

Sort by score

Write sort_by_score(people) that takes a structured array with a "score" field and returns it sorted in ascending order by that field.

💡 Hint

np.sort takes an order= keyword for structured arrays — np.sort(people, order="score").

✅ Solution
def sort_by_score(people):
    return np.sort(people, order="score")