0
0
NumPydata~5 mins

Accessing fields by name in NumPy

Choose your learning style9 modes available
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.

You have a table of data with named columns and want to get one column.
You want to analyze or modify only one part of a structured dataset.
You need to filter or summarize data based on a specific field.
You want to print or visualize just one attribute from many records.
Syntax
NumPy
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.

Examples
Get the 'x' field values from the structured array.
NumPy
data = np.array([(1, 2.0), (3, 4.0)], dtype=[('x', 'i4'), ('y', 'f4')])
x_values = data['x']
Get the 'y' field values from the same array.
NumPy
y_values = data['y']
Sample Program

This program creates a structured array with names and ages. Then it accesses each field by name and prints the results.

NumPy
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)
OutputSuccess
Important Notes

Field names are case-sensitive.

You can access multiple fields by combining arrays or using views.

Summary

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.