1

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)])     

1 Answer 1

1

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')]
Sign up to request clarification or add additional context in comments.

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.