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?
There is no shortcut. You would just construct the new dtype however you like and use .astype()
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With