NumPy: programmatically modifies the 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 "Col2" to a string. How can I change dtype to do this, for example, in a non-programmatic way:

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

where new_sa now looks, which is fine:

 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 to programmatically change orig_type to new_type ? (don't worry about the length |S10 ). Is there a β€œsimple” way, or do I need a for loop to create a new dtype constructor dtype ?

+6
source share
2 answers

If your question is actually focused on how to build a new dtype object from the old one, this might 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) 
+4
source

There is no shortcut. You would just create a new dtype type as you like and use .astype() .

+5
source

Source: https://habr.com/ru/post/887423/


All Articles