w3resource

Combine two Structured arrays in NumPy

NumPy: Structured Arrays Exercise-10 with Solution

Combining Structured Arrays:

Write a NumPy program that combines two structured arrays with the same dtype into one.

Sample Solution:

Python Code:

import numpy as np

# Define the data type for the structured arrays
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]

# Create the first structured array with sample data
structured_array1 = np.array([
    ('Lehi', 25, 5.5),
    ('Albin', 30, 5.8)
], dtype=dtype)

# Create the second structured array with sample data
structured_array2 = np.array([
    ('Zerach', 35, 6.1),
    ('Edmund', 40, 5.9),
    ('Laura', 28, 5.7)
], dtype=dtype)


print("Original Structured Arrays:")
print(structured_array1)
print(structured_array2)

# Combine the two structured arrays into one
combined_array = np.concatenate((structured_array1, structured_array2))

# Print the combined structured array
print("\nCombined Structured Array:")
print(combined_array)

Output:

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

Combined Structured Array:
[('Lehi', 25, 5.5) ('Albin', 30, 5.8) ('Zerach', 35, 6.1)
 ('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 arrays 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 the First Structured Array:
    • Created the first structured array structured_array1 using np.array(), providing sample data for two individuals.
  • Create a Second Structured Array:
    • Created the second structured array structured_array2 using np.array(), providing sample data for three individuals.
  • Combine Structured Arrays:
    • Combine the two structured arrays into one using "np.concatenate()".
  • Print Combined Structured Array:
    • Print the combined structured array to verify the result.

Python-Numpy Code Editor:

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

Previous: Increase Age field in NumPy Structured array by 1.
Next: Split NumPy Structured array based on condition.

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://198.211.115.131/python-exercises/numpy/combine-two-structured-arrays-in-numpy.php