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
Defining structured dtypes in NumPy
📖 Scenario: You work in a small company that collects information about employees. You want to store each employee's name, age, and salary in a structured way using NumPy.
🎯 Goal: Create a NumPy structured array with a custom data type that holds employee name as a string, age as an integer, and salary as a float. Then, display the array.
📋 What You'll Learn
Create a structured dtype with fields: 'name' (string of length 10), 'age' (integer), and 'salary' (float).
Create a NumPy array called employees with exactly 3 entries using the structured dtype.
Fill the array with these exact employee data: ('Alice', 30, 70000.0), ('Bob', 25, 48000.5), ('Charlie', 35, 120000.0).
Print the employees array to show the stored data.
💡 Why This Matters
🌍 Real World
Structured dtypes help store complex data like employee records, sensor data, or any tabular data with mixed types efficiently in NumPy.
💼 Career
Knowing how to define and use structured dtypes is useful for data scientists and analysts working with heterogeneous datasets in Python.
Progress0 / 4 steps
1
Create the structured dtype
Create a NumPy structured dtype called employee_dtype with these fields: 'name' as a string of length 10, 'age' as an integer, and 'salary' as a float.
NumPy
Hint
Use np.dtype with a list of tuples. Each tuple has the field name and the data type.
2
Create the employees array
Create a NumPy array called employees with 3 entries using the employee_dtype dtype. Fill it with these exact data: ('Alice', 30, 70000.0), ('Bob', 25, 48000.5), ('Charlie', 35, 120000.0).
NumPy
Hint
Use np.array with a list of tuples and specify dtype=employee_dtype.
3
Access and print the employee names
Use a for loop with variable employee to iterate over employees. Inside the loop, print only the name field of each employee.
NumPy
Hint
Use for employee in employees: and inside print employee['name'].
4
Print the full employees array
Print the entire employees array to display all employee data.
NumPy
Hint
Use print(employees) to show the full array.
Practice
(1/5)
1. What is the main purpose of defining a structured dtype in numpy?
easy
A. To convert arrays into lists automatically
B. To create arrays with only one data type
C. To speed up mathematical operations on arrays
D. To combine multiple data types in one array with named fields
Solution
Step 1: Understand structured dtype concept
Structured dtypes allow combining different data types in one array with named fields.
Step 2: Compare options with concept
Only To combine multiple data types in one array with named fields correctly describes this purpose; others describe unrelated features.
Final Answer:
To combine multiple data types in one array with named fields -> Option D
Quick Check:
Structured dtype = combine types [OK]
Hint: Structured dtype means named fields with different types [OK]
Common Mistakes:
Thinking structured dtype is for single data type arrays
Confusing structured dtype with speed optimization
Believing it converts arrays to lists
2. Which of the following is the correct syntax to define a structured dtype with fields 'name' as string and 'age' as integer?
easy
A. dtype = [('name', 'U10'), ('age', 'i4')]
B. dtype = ['name': 'U10', 'age': 'i4']
C. dtype = {'name': 'U10', 'age': 'i4'}
D. dtype = [('name', 10), ('age', int)]
Solution
Step 1: Recall structured dtype syntax
Structured dtype is defined as a list of tuples with (field_name, data_type).
Step 2: Check each option
dtype = [('name', 'U10'), ('age', 'i4')] matches the correct syntax; others use invalid formats or types.
Final Answer:
dtype = [('name', 'U10'), ('age', 'i4')] -> Option A
Quick Check:
List of tuples = correct dtype syntax [OK]
Hint: Use list of (field, type) tuples for structured dtype [OK]
Common Mistakes:
Using dictionary instead of list of tuples
Using colon instead of comma inside tuples
Using integer 10 instead of string 'U10' for string length
3. What will be the output of this 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. [9.5 8. ]
B. [(1, 9.5) (2, 8.0)]
C. [1 2]
D. Error: invalid field name
Solution
Step 1: Understand structured array creation
Array has fields 'id' (int) and 'score' (float). Data has two records.
Step 2: Access 'score' field
Printing data['score'] returns array of scores: [9.5, 8.0].
Final Answer:
[9.5 8. ] -> Option A
Quick Check:
Access field returns values [9.5 8.0] [OK]
Hint: Access field by name to get its values array [OK]
Common Mistakes:
Expecting full tuples instead of single field values
Confusing field names causing errors
Printing whole array instead of one field
4. Identify the error in this code snippet:
import numpy as np
dtype = [('name', 'U5'), ('age', 'i4')]
data = np.array([('Alice', 25), ('Bob', 30)], dtype=dtype)
print(data['age'])
medium
A. Missing parentheses in np.array call
B. No error, code runs fine
C. Incorrect dtype format, should be dictionary
D. Field 'name' length too short for 'Alice'
Solution
Step 1: Check string length for 'name' field
'U5' means max 5 characters, but 'Alice' has 5 characters, which fits exactly.
Step 2: Verify if any error occurs
Actually, 'Alice' fits in 'U5', so no error from length. Check other options.
Step 3: Re-examine options
Options B, C, and D incorrectly identify non-existent errors; the code runs fine.
Final Answer:
No error, code runs fine -> Option B
Quick Check:
String length fits exactly, no error [OK]
Hint: Check string length carefully; exact fit is allowed [OK]
Common Mistakes:
Assuming string length must be larger than string length
Confusing dtype syntax with dictionary
Thinking missing parentheses cause error here
5. You want to create a structured array to store employee data with fields: 'emp_id' (integer), 'name' (string max 8 chars), and 'salary' (float). Which dtype definition is correct and why?