Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create a compound dtype numpy array from existing individual vectors?

I am learning about dtypes in numpy and I have the following doubt.

I can define a compound type as follows:

myrecord = np.dtype([
    ('col1', 'u4'),
    ('col2', 'f8')
])

If I have two individual numpy arrays:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a=np.array([1,2,3,4])
b=np.array([10.1,20.1,30.1,40.1])

How would I generate a third array c of type my_record?

This is what I tried, which it does not work but it might give an idea on what I am looking for:

c=np.array((a,b), dtype=myrecord)

This would be the expected output:

array([(1, 10.1),
       (2, 20.1),
       (3, 30.1),
       (4, 40.1),],
      dtype=[('col1', '<u4'),('col2', '<f8')])

>Solution :

You’re almost there! You have to zip the a and b columns together when creating c:

import numpy as np

myrecord = np.dtype([
    ('col1', 'u4'),
    ('col2', 'f8')
])

a=np.array([1,2,3,4])
b=np.array([10.1,20.1,30.1,40.1])

c = np.array(list(zip(a, b)), dtype=myrecord)

Then when we view c, you get the desired result:

>>>c
array([(1, 10.1), (2, 20.1), (3, 30.1), (4, 40.1)],
      dtype=[('col1', '<u4'), ('col2', '<f8')])

Your example code is trying to create a tuple of arrays. What you really wanted is an array of tuples.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading