NumPy: programmatically modify dtype of a structured array

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?

6
задан Mike T 6 May 2011 в 03:20
поделиться