Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Why structured arrays matter
📖 Scenario: Imagine you work at a small library. You have a list of books, and each book has a title, an author, and a year it was published. You want to keep all this information together in one place so you can easily find and use it.
🎯 Goal: You will create a structured array using numpy to store information about books. Then, you will access and print the data to see why structured arrays are useful for keeping related data organized.
📋 What You'll Learn
Use numpy to create a structured array
Include fields: title (string), author (string), and year (integer)
Access and print the structured array data
💡 Why This Matters
🌍 Real World
Libraries, stores, and many businesses keep records with different types of information together, like names, dates, and numbers.
💼 Career
Data scientists and analysts often use structured arrays to organize and analyze complex data efficiently.
Progress0 / 4 steps
1
Create a structured array with book data
Import numpy as np. Create a structured array called books with three entries. Each entry should have these fields: title (string of max length 20), author (string of max length 20), and year (integer). Use these exact values: ('The Hobbit', 'Tolkien', 1937), ('1984', 'Orwell', 1949), and ('Python 101', 'Smith', 2020).
NumPy
Hint
Use np.array with a dtype that defines the fields and their types.
2
Create a variable to hold the field names
Create a variable called fields that holds the list of field names in the books structured array. Use books.dtype.names to get the field names.
NumPy
Hint
Use books.dtype.names to get the tuple of field names.
3
Access the 'author' field from the structured array
Use the variable books to get all the authors. Create a variable called authors that contains the author field from books.
NumPy
Hint
Access a field in a structured array by using array['field_name'].
4
Print the structured array and the authors
Print the entire books structured array. Then print the authors variable.
NumPy
Hint
Use two print statements: one for books and one for authors.
Practice
(1/5)
1. What is the main advantage of using numpy structured arrays?
easy
A. They automatically visualize data.
B. They only store integers efficiently.
C. They replace Python lists completely.
D. They allow storing different data types in one array with named fields.
Solution
Step 1: Understand structured arrays
Structured arrays let you store multiple data types together, like numbers and text, in one array with named fields.
Step 2: Compare options
Only They allow storing different data types in one array with named fields. correctly describes this main advantage. Others are incorrect or unrelated.
Final Answer:
They allow storing different data types in one array with named fields. -> Option D
Quick Check:
Structured arrays = multiple types + named fields [OK]
Hint: Remember: structured arrays hold mixed data types by field names [OK]
Common Mistakes:
Thinking structured arrays only hold one data type
Confusing structured arrays with visualization tools
Assuming structured arrays replace all Python lists
2. Which of the following is the correct way to define a structured array with fields 'name' (string) and 'age' (integer)?
easy
A. np.array([('Alice', 25), ('Bob', 30)], dtype=[('name', 'int'), ('age', 'float')])
B. np.array([(b'Alice', 25), (b'Bob', 30)], dtype=[('name', 'S10'), ('age', 'i4')])
C. np.array([('Alice', 25), ('Bob', 30)], dtype=[('age', 'i4'), ('name', 'S10')])
D. np.array(['Alice', 25, 'Bob', 30], dtype=[('name', 'S10'), ('age', 'i4')])
Solution
Step 1: Check data and dtype match
np.array([(b'Alice', 25), (b'Bob', 30)], dtype=[('name', 'S10'), ('age', 'i4')]) correctly uses byte strings for names and integer type for age, matching the dtype fields.
Step 2: Identify errors in other options
B uses wrong types ('int' for name, 'float' for age); C passes string first ('Alice') to 'age' ('i4'), causing type mismatch; D passes a flat list instead of tuples.
C. Field 'age' does not exist in the structured array.
D. Array creation syntax is invalid.
Solution
Step 1: Check dtype fields
The structured array has fields 'id' and 'name', but no 'age' field.
Step 2: Analyze the print statement
Trying to print arr['age'] causes an error because 'age' is not defined in dtype.
Final Answer:
Field 'age' does not exist in the structured array. -> Option C
Quick Check:
Accessing undefined field = error [OK]
Hint: Check field names carefully before accessing [OK]
Common Mistakes:
Assuming all fields exist by default
Ignoring dtype field names
Confusing data values with field names
5. You have a structured array with fields 'name' (string), 'age' (int), and 'score' (float). How can you sort this array first by 'age' ascending, then by 'score' descending?
hard
A. Use arr['score'] = -arr['score'] arr.sort(order=['age', 'score'])
B. Use np.sort(arr, order=['age', 'score']) with a custom comparator for descending score.
C. Use arr.sort(order=['age']) then arr['score'] = -arr['score'] before sorting again.
D. Use arr.sort(order=['age']) then arr[arr['age'] == age_value].sort(order='score') for each age.
Solution
Step 1: Understand sorting by multiple fields
NumPy structured arrays can be sorted by multiple fields using sort(order=[...]), but only ascending.
Step 2: Handle descending order
To sort 'score' descending, negate it first (arr['score'] = -arr['score']), then arr.sort(order=['age', 'score']). This sorts age ascending, then negated score ascending (original score descending).
Final Answer:
Use arr['score'] = -arr['score'] arr.sort(order=['age', 'score']) -> Option A