Introduction
Accessing fields by name lets you get specific parts of structured data easily. It helps you work with complex data like tables or records.
Jump into concepts and practice - no test required
Accessing fields by name lets you get specific parts of structured data easily. It helps you work with complex data like tables or records.
array['field_name']The array must be a structured numpy array with named fields.
Use the field name as a string inside square brackets to get that column.
data = np.array([(1, 2.0), (3, 4.0)], dtype=[('x', 'i4'), ('y', 'f4')]) x_values = data['x']
y_values = data['y']This program creates a structured array with names and ages. Then it accesses each field by name and prints the results.
import numpy as np # Create a structured array with fields 'name' and 'age' data = np.array([('Alice', 25), ('Bob', 30), ('Cathy', 22)], dtype=[('name', 'U10'), ('age', 'i4')]) # Access the 'name' field names = data['name'] # Access the 'age' field ages = data['age'] print('Names:', names) print('Ages:', ages)
Field names are case-sensitive.
You can access multiple fields by combining arrays or using views.
Structured arrays let you store data with named fields.
Access fields by using the field name in square brackets.
This makes it easy to work with parts of complex data.
'age' from a NumPy structured array data?data['age'] correctly accesses the 'age' field. Other options use incorrect methods or syntax.'name' (string) and 'score' (integer)?arr = np.array([(1, 2.5), (3, 4.5)], dtype=[('x', 'i4'), ('y', 'f4')]), what is the output of arr['y']?arr['y'] returns an array of the 'y' values: [2.5, 4.5].arr = np.array([(1, 2), (3, 4)], dtype=[('id', 'i4'), ('b', 'i4')])
print(arr.a)arr.a causes AttributeError because 'a' is not an attribute but a field name.data with fields 'name' (string), 'age' (int), and 'score' (float). How do you create a new array containing only the 'name' and 'score' fields?data[['name', 'score']] returns a new structured array with only those fields.