w3resource

Sort records by Height in NumPy Structured array

NumPy: Structured Arrays Exercise-6 with Solution

Sorting Records:

Write a NumPy program that sorts the structured array created with fields for 'name' (string), 'age' (integer), and 'height' (float), by the 'height' field in ascending order and prints the sorted array.

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:")
print(structured_array)

# Sort the structured array by the 'height' field in ascending order
sorted_array = np.sort(structured_array, order='height')

# Print the sorted structured array
print("\nSorted Structured Array by 'height' (ascending order):")
print(sorted_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)]

Sorted Structured Array by 'height' (ascending order):
[('Lehi Piero', 25, 5.5) ('Laura Feli', 28, 5.7) ('Albin Acha', 30, 5.8)
 ('Edmund Ter', 40, 5.9) ('Zerach Hav', 35, 6.1)]

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 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'.
  • Sort Records:
    • Sorted the structured array by the 'height' field in ascending order using np.sort() and specified the field to sort by with the order parameter.
  • Print Sorted Records:
    • Finally print the sorted structured array to display the individuals ordered by height in ascending order.

Python-Numpy Code Editor:

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

Previous: Filter records by age in NumPy Structured array.
Next: Calculate average Age 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/sort-records-by-height-in-numpy-structured-array.php