w3resource

Delete record by Name in NumPy Structured array

NumPy: Structured Arrays Exercise-8 with Solution

Deleting records:

Write a NumPy program to delete the record where 'name' is a specific name from 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', 25, 5.5),
    ('Albin', 30, 5.8),
    ('Zerach', 35, 6.1),
    ('Edmund', 40, 5.9),
    ('Laura', 28, 5.7)
], dtype=dtype)


print("Original Structured Array:")
print(structured_array)

# Specify the name of the record to delete
name_to_delete = 'Zerach'

# Delete the record where 'name' is the specified name
# Use a boolean mask to filter out the record with the specified name
filtered_array = structured_array[structured_array['name'] != name_to_delete]

# Print the updated structured array
print("\nUpdated Structured Array after deleting the record where 'name' is '{}':\n".format(name_to_delete))
print(filtered_array)

Output:

Original Structured Array:
[('Lehi', 25, 5.5) ('Albin', 30, 5.8) ('Zerach', 35, 6.1)
 ('Edmund', 40, 5.9) ('Laura', 28, 5.7)]

Updated Structured Array after deleting the record where 'name' is 'Zerach':

[('Lehi', 25, 5.5) ('Albin', 30, 5.8) ('Edmund', 40, 5.9)
 ('Laura', 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'.
  • Specify the Name to delete:
    • Specify the name of the record to delete, in this case, 'Charlie'.
  • Delete the record:
    • Use a boolean mask to filter out the record with the specified name by checking if the 'name' field is not equal to the specified name. The filtered array contains all records except the one with the specified name.
  • Print Updated Structured Array:
    • Print the updated structured array to verify that the record with the specified name has been deleted.

Python-Numpy Code Editor:

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

Previous: Calculate average Age in NumPy Structured array.
Next: Increase Age field in NumPy Structured array by 1.

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.