0
0
NumPydata~15 mins

Accessing fields by name in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing Fields by Name in NumPy Structured Arrays
📖 Scenario: You work in a small store and keep track of products using a table with columns for product name, price, and quantity.
🎯 Goal: You will create a structured NumPy array to store product data, then access the price field by its name to see the prices of all products.
📋 What You'll Learn
Create a NumPy structured array with fields 'name', 'price', and 'quantity'.
Use a configuration variable to select the field name 'price'.
Access the 'price' field from the structured array using the field name.
Print the prices of all products.
💡 Why This Matters
🌍 Real World
Stores and businesses often keep product data in tables with named columns. Accessing fields by name helps quickly get specific information like prices or quantities.
💼 Career
Data scientists and analysts use structured arrays or tables to organize data. Knowing how to access fields by name is essential for data cleaning, analysis, and reporting.
Progress0 / 4 steps
1
Create a NumPy structured array with product data
Import NumPy as np. Create a structured array called products with three entries. Each entry should have fields: 'name' (string of length 10), 'price' (float), and 'quantity' (integer). Use these exact values: ('apple', 0.5, 10), ('banana', 0.3, 20), ('orange', 0.8, 15).
NumPy
Need a hint?

Use np.array with a list of tuples and specify dtype as a list of tuples with field names and types.

2
Set a variable for the field name to access
Create a variable called field_name and set it to the string 'price'. This will help us select the price field later.
NumPy
Need a hint?

Just assign the string 'price' to the variable field_name.

3
Access the price field using the field name variable
Use the variable field_name to access the price field from the products array. Store the result in a variable called prices.
NumPy
Need a hint?

Use products[field_name] to get the array of prices.

4
Print the prices of all products
Print the variable prices to display the prices of all products.
NumPy
Need a hint?

Use print(prices) to show the prices.