w3resource

Broadcast value across field in NumPy Structured array


NumPy: Structured Arrays Exercise-20 with Solution


Broadcasting with Structured Arrays:

Write a NumPy program to broadcast a value (e.g., set all 'height' values to 6.0) across the 'height' field in the structured array created with fields for 'name' (string), 'age' (integer), and 'height' (float).

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)

print("Original structured array: ",structured_array)

# Broadcast a value (e.g., set all 'height' values to 6.0) across the 'height' field
structured_array['height'] = 6.0

# Print the updated structured array
print("\nStructured Array with all 'height' values set to 6.0:")
print(structured_array)

Output:

Original structured array:  [('Lehi Piero', 25, 5.5) ('Albin Acha', 30, 5.8) ('Zerach Hav', 35, 6.1)
 ('Edmund Ter', 40, 5.9) ('Laura Feli', 28, 5.7)]

Structured Array with all 'height' values set to 6.0:
[('Lehi Piero', 25, 6.) ('Albin Acha', 30, 6.) ('Zerach Hav', 35, 6.)
 ('Edmund Ter', 40, 6.) ('Laura Feli', 28, 6.)]

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 a 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'.
  • Broadcast value:
    • Broadcast a value by setting all 'height' field values to 6.0 using structured_array['height'] = 6.0.
  • Print the updated structured array to verify that all 'height' values have been set to 6.0.

Python-Numpy Code Editor: