w3resource

Select records with advanced indexing in NumPy Structured array

NumPy: Structured Arrays Exercise-18 with Solution

Advanced indexing:

Write a NumPy program that uses advanced indexing to select records from the structured array created with fields for 'name' (string), 'age' (integer), and 'height' (float) where both 'age' is greater than 25 and 'height' is less than 6.0.

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)

# Use advanced indexing to select records where age > 25 and height < 6.0
selected_records = structured_array[(structured_array['age'] > 25) & (structured_array['height'] < 6.0)]

# Print the selected records
print("\nRecords where age > 25 and height < 6.0:")
print(selected_records)

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)]

Records where age > 25 and height < 6.0:
[('Albin Acha', 30, 5.8) ('Edmund Ter', 40, 5.9) ('Laura Feli', 28, 5.7)]

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'.
  • Advanced indexing:
    • Used advanced indexing to select records where the 'age' field is greater than 25 and the 'height' field is less than 6.0. This was done using a boolean mask that combines the two conditions.
  • Print the selected records to verify the correct application of the advanced indexing.

Python-Numpy Code Editor:

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

Previous: Create Structured array with nested fields in NumPy.
Next: Merge fields into a new field 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.