0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.