6

I have a structured array, for example:

import numpy as np
orig_type = np.dtype([('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')])
sa = np.empty(4, dtype=orig_type)

where sa looks like (random data):

array([(11772880L, 14527168, 1.079593371731406e-307),
       (14528064L, 21648608, 1.9202565460908188e-302),
       (21651072L, 21647712, 1.113579933986867e-305),
       (10374784L, 1918987381, 3.4871913811200906e-304)], 
      dtype=[('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')])

Now, in my program, I somehow decide that I need to change the data type of 'Col2' to a string. How can I modify the dtype to do this, for example the non-programmatic way:

new_type = np.dtype([('Col1', '<u4'), ('Col2', '|S10'), ('Col3', '<f8')])
new_sa = sa.astype(new_type)

where new_sa now looks like, which is great:

array([(11772880L, '14527168', 1.079593371731406e-307),
       (14528064L, '21648608', 1.9202565460908188e-302),
       (21651072L, '21647712', 1.113579933986867e-305),
       (10374784L, '1918987381', 3.4871913811200906e-304)], 
      dtype=[('Col1', '<u4'), ('Col2', '|S10'), ('Col3', '<f8')])

How do I programmatically modify orig_type to new_type? (don't worry about the length |S10). Is there an "easy" way, or do I need a for-loop to construct a new dtype constructor object?

2 Answers 2

5

There is no shortcut. You would just construct the new dtype however you like and use .astype().

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

Comments

4

If your question actually aims at how to construct the new dtype object from the old one, this may be what you are looking for:

orig_type = sa.dtype
descr = orig_type.descr
descr[1] = (descr[1][0], "|S10")
new_type = numpy.dtype(descr)

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.