w3resource

Access and print 'Name' Field from NumPy Structured array


NumPy: Structured Arrays Exercise-2 with Solution


Accessing Specific Fields:

Write a NumPy program that accesses and prints all values of the 'Name' field from the structured array created in exercise.

Sample Solution:

Python Code:

import numpy as np

# Define the data type for the structured array
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]

# Create the structured array with sample data
structured_array = np.array([
    ('Lehi Piero', 25, 5.5),
    ('Albin Achan', 30, 5.8),
    ('Zerach Hava', 35, 6.1),
    ('Edmund Tereza', 40, 5.9),
    ('Laura Felinus', 28, 5.7)
], dtype=dtype)


# Access and print all values of the 'name' field
# Access the 'name' field from the structured array
name_field_values = structured_array['name']

# Print all values of the 'name' field
print("All values of the 'name' field:")
print(name_field_values)

Output:

All values of the 'name' field:
['Lehi Piero' 'Albin Acha' 'Zerach Hav' 'Edmund Ter' 'Laura Feli']

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Define Data Type:
    • Define the data type for the structured array using a list of tuples. Each tuple specifies a field name and its corresponding data type. The data types are:
      • 'U10' for a string of up to 10 characters.
      • 'i4' for a 4-byte integer.
      • 'f4' for a 4-byte float.
  • Create Structured Array:
    • Created the structured array using np.array(), providing sample data for five individuals. Each individual is represented as a tuple with values for 'name', 'age', and 'height'.
  • Access and Print 'Name' Field Values:
    • Access the 'name' field from the structured array using structured_array['name'].
    • Print all values of the 'name' field.

Python-Numpy Code Editor: