w3resource

Create Structured array with nested fields in NumPy

NumPy: Structured Arrays Exercise-17 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/create-structured-array-with-nested-fields-in-numpy.php