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

Time:07-08

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:

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

CodePudding user response:

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.

  • Related