w3resource

Create Structured array with nested fields in NumPy


17. Structured Array with Nested Fields

Creating a Structured Array with Nested Fields:

Write a NumPy program that creates a structured array with nested fields, such as 'person' (which has sub-fields 'name' and 'age') and 'score' (integer).

Sample Solution:

Python Code:

import numpy as np

# Define the data type for the structured array with nested fields
dtype = [('person', [('name', 'U10'), ('age', 'i4')]), ('score', 'i4')]

# Create the structured array with sample data
structured_array = np.array([
    (('Elsi Eunomia', 25), 85),
    (('Sonia Husein', 30), 90),
    (('Carmen Hildur', 35), 95),
    (('Lino Prakash', 40), 80),
    (('Eshe Waldemar', 28), 88)
], dtype=dtype)

# Print the structured array with nested fields
print("Structured Array with Nested Fields:")
print(structured_array)

Output:

Structured Array with Nested Fields:
[(('Elsi Eunom', 25), 85) (('Sonia Huse', 30), 90)
 (('Carmen Hil', 35), 95) (('Lino Praka', 40), 80)
 (('Eshe Walde', 28), 88)]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Define Data Type:
    • Define the data type for the structured array with nested fields. The data type is specified as a list of tuples, where:
      • 'person' is a field that contains sub-fields 'name' (a string of up to 10 characters) and 'age' (a 4-byte integer).
      • 'score' is a field that is a 4-byte integer.
  • 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 'person' (which includes 'name' and 'age') and 'score'.
  • Finally print the structured array to display the data with nested fields.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to create a structured array with a nested field 'person' containing 'name' and 'age', then print the nested data.
  • Write a Numpy program to access nested fields in a structured array and perform arithmetic operations on the 'age' sub-field.
  • Write a Numpy program to update a nested field within a structured array and verify the changes with deep indexing.
  • Write a Numpy program to create a structured array with nested fields and then flatten the structure into a regular array with compound dtypes.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Iterate over records in NumPy Structured array.
Next: Select records with advanced indexing in NumPy Structured array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.