0
0
NumPydata~30 mins

Defining structured dtypes in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(employees) to show the full array.