Bird
Raised Fist0
NumPydata~20 mins

Creating structured arrays in NumPy - Practice Exercises

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Structured Arrays Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a structured array creation
What is the output of this code that creates a structured array with fields 'name' and 'age'?
NumPy
import numpy as np

person = np.array([('Alice', 25), ('Bob', 30)], dtype=[('name', 'U10'), ('age', 'i4')])
print(person)
A])03 ,'boB'( )52 ,'ecilA'([
B[('Alice', '25') ('Bob', '30')]
C[('Alice', 25) ('Bob', 30)]
D[('Alice', 25) ('Bob', 30) ('Charlie', 35)]
Attempts:
2 left
💡 Hint
Look at the dtype and how the values are stored as integers or strings.
❓ data_output
intermediate
1:30remaining
Number of elements in a structured array
How many elements are in this structured array?
NumPy
import numpy as np

arr = np.array([(1, 2.5), (3, 4.5), (5, 6.5)], dtype=[('x', 'i4'), ('y', 'f4')])
print(len(arr))
A1
B2
C6
D3
Attempts:
2 left
💡 Hint
Count the number of tuples in the array creation.
🔧 Debug
advanced
2:00remaining
Identify the error in structured array creation
What error does this code raise when trying to create a structured array?
NumPy
import numpy as np

arr = np.array([(1, 2.5), (3, '4.5')], dtype=[('x', 'i4'), ('y', 'f4')])
AValueError: could not convert string to float: '4.5'
BTypeError: data type mismatch
CSyntaxError: invalid syntax
DNo error, array created successfully
Attempts:
2 left
💡 Hint
Check the data types and the values provided for each field.
🚀 Application
advanced
1:30remaining
Accessing fields in a structured array
Given this structured array, what is the output of printing arr['age']?
NumPy
import numpy as np

arr = np.array([('John', 28), ('Jane', 32)], dtype=[('name', 'U10'), ('age', 'i4')])
print(arr['age'])
A[('John', 28) ('Jane', 32)]
B[28 32]
C['John' 'Jane']
D[28, 32]
Attempts:
2 left
💡 Hint
Accessing a field returns an array of that field's values.
🧠 Conceptual
expert
2:30remaining
Memory layout of structured arrays
Which statement about the memory layout of numpy structured arrays is TRUE?
AStructured arrays store data as a single contiguous block with fields laid out in order, enabling efficient memory use.
BEach field in a structured array is stored in a separate numpy array internally.
CStructured arrays cannot store mixed data types in the same array.
DStructured arrays store all fields contiguously in memory, allowing fast access to any field.
Attempts:
2 left
💡 Hint
Think about how numpy stores data for performance and memory efficiency.

Practice

(1/5)
1. What is the main purpose of creating a structured array in numpy?
easy
A. To create arrays with only one data type
B. To store data with different types in named fields within one array
C. To speed up numerical calculations on large arrays
D. To visualize data using plots

Solution

  1. Step 1: Understand structured arrays

    Structured arrays allow storing mixed data types in one array with named fields.
  2. Step 2: Compare options

    Only To store data with different types in named fields within one array correctly describes this purpose; others describe unrelated features.
  3. Final Answer:

    To store data with different types in named fields within one array -> Option B
  4. Quick Check:

    Structured arrays = mixed types + named fields [OK]
Hint: Structured arrays hold mixed data types with names [OK]
Common Mistakes:
  • Thinking structured arrays only hold one data type
  • Confusing structured arrays with plotting functions
  • Assuming structured arrays speed up all calculations
2. Which of the following is the correct way to define a structured array dtype with fields 'name' (string) and 'age' (integer)?
easy
A. dtype = [('name', 'U10'), ('age', 'i4')]
B. dtype = ['name': str, 'age': int]
C. dtype = {'name': 'string', 'age': 'int'}
D. dtype = [('name', str), ('age', float)]

Solution

  1. Step 1: Recall dtype syntax for structured arrays

    Structured array dtypes are defined as a list of tuples: (field_name, data_type).
  2. Step 2: Check each option

    dtype = [('name', 'U10'), ('age', 'i4')] uses correct tuple syntax with numpy string and integer types. Others use invalid syntax or wrong types.
  3. Final Answer:

    dtype = [('name', 'U10'), ('age', 'i4')] -> Option A
  4. Quick Check:

    Structured dtype = list of (name, type) tuples [OK]
Hint: Use list of (field, type) tuples for dtype [OK]
Common Mistakes:
  • Using dictionary syntax instead of list of tuples
  • Using Python types instead of numpy dtype strings
  • Mixing float type for integer fields
3. What will be the output of the following code?
import numpy as np
dtype = [('id', 'i4'), ('score', 'f4')]
data = np.array([(1, 9.5), (2, 8.0)], dtype=dtype)
print(data['score'])
medium
A. Error: KeyError
B. [1 2]
C. [(1, 9.5) (2, 8.0)]
D. [9.5 8. ]

Solution

  1. Step 1: Understand structured array creation

    The array has fields 'id' (int) and 'score' (float), with two records.
  2. Step 2: Access the 'score' field

    Accessing data['score'] returns an array of the 'score' values: [9.5, 8.0].
  3. Final Answer:

    [9.5 8. ] -> Option D
  4. Quick Check:

    Accessing field returns array of that column [OK]
Hint: Access fields by name to get column arrays [OK]
Common Mistakes:
  • Expecting full records instead of single field
  • Confusing field names causing KeyError
  • Thinking output is list of tuples
4. Identify the error in the following code that tries to create a structured array:
import numpy as np
dtype = [('name', 'U5'), ('age', 'i4')]
data = np.array([('Alice', 25), ('Bob', 30)], dtype=dtype)
print(data['age'])
medium
A. The dtype definition is missing field names
B. The tuple elements should be lists, not tuples
C. No error; code runs correctly
D. The string length 'U5' is too short for 'Alice'

Solution

  1. Step 1: Check dtype and data compatibility

    'U5' means Unicode string of length 5, 'Alice' has 5 characters, so it fits.
  2. Step 2: Verify data structure and code correctness

    Data is a list of tuples matching dtype fields; code runs without error and prints ages.
  3. Final Answer:

    No error; code runs correctly -> Option C
  4. Quick Check:

    String length matches field size; tuples allowed [OK]
Hint: Check string length matches longest string [OK]
Common Mistakes:
  • Assuming string length too short causes error
  • Thinking tuples are invalid for data input
  • Believing dtype must be dictionary
5. You have a list of employee data: [('John', 28, 50000), ('Jane', 32, 60000), ('Doe', 24, 45000)]. How do you create a structured array with fields 'name' (string, max 10 chars), 'age' (int), and 'salary' (float) to store this data?
hard
A. dtype = [('name', 'U10'), ('age', 'i4'), ('salary', 'f8')]; np.array(data, dtype=dtype)
B. dtype = [('name', str), ('age', int), ('salary', float)]; np.array(data)
C. dtype = {'name': 'U10', 'age': 'i4', 'salary': 'f8'}; np.array(data)
D. dtype = [('name', 'S10'), ('age', 'i4'), ('salary', 'f4')]; np.array(data)

Solution

  1. Step 1: Define correct dtype for fields

    Use list of tuples with field names and numpy types: 'U10' for Unicode string max 10 chars, 'i4' for int, 'f8' for float64.
  2. Step 2: Create structured array with data and dtype

    Pass data and dtype to np.array to create structured array storing all fields correctly.
  3. Final Answer:

    dtype = [('name', 'U10'), ('age', 'i4'), ('salary', 'f8')]; np.array(data, dtype=dtype) -> Option A
  4. Quick Check:

    Use list of (field, type) tuples and pass dtype [OK]
Hint: Use Unicode string 'U10' for names, correct numeric types [OK]
Common Mistakes:
  • Using Python types instead of numpy dtype strings
  • Using dictionary instead of list of tuples for dtype
  • Choosing byte string 'S10' instead of Unicode 'U10'