I have NumPy structured array data
:
data_tup = [tuple(ele) for ele in array]
data = np.array(
data_tup,
dtype = [("field_1", "<U30"), ("field_2", "<U30"),
("field_3", "<U30"), ("field_4", "<U30"),
("field_5", "<U30"), ("field_6", "<U30"),
("field_7", "<U30"), ("field_8", "<U30"),
("field_9", "<U30")])
I want to change the data types of all fields in data
to float
, except for fields specified by a list indices
which holds the index values of the fields in dtype
that should not change data types.
For example:
indices = [0, 4, 5, 7]
data = np.array(
data_tup,
dtype = [("field_1", "<U30"), ("field_2", "<U30"),
("field_3", "<U30"), ("field_4", "<U30"),
("field_5", "<U30"), ("field_6", "<U30"),
("field_7", "<U30"), ("field_8", "<U30"),
("field_9", "<U30")])
New dtype
in data
should now be:
dtype = [("field_1", "<U30"), ("field_2", float),
("field_3", float), ("field_4", float),
("field_5", "<U30"), ("field_6", "<U30"),
("field_7", float), ("field_8", "<U30"),
("field_9", float)])
A list of tuples is the easiest way to convert between dtypes like this:
In [63]: data = [('123','456')]
In [64]: np.array(data, dtype='U10,U10')
Out[64]: array([('123', '456')], dtype=[('f0', '<U10'), ('f1', '<U10')])
In [65]: np.array(data, dtype='U10,float')
Out[65]: array([('123', 456.)], dtype=[('f0', '<U10'), ('f1', '<f8')])
If starting with the all-string dtype array:
In [77]: np.array(data, dtype='U10,U10').tolist()
Out[77]: [('123', '456')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.