0

I have a list of strings string_list that I want to convert to a 1-element structured numpy array of pre-specified dtype:

string_list = ['123', '45', '6.7']
my_dtype = np.dtype([('a','i4'),('b','f4'),('c','f8')])

The output result I want is:

array([(123, 45., 6.7)], dtype=[('a', '<i4'), ('b', '<f4'), ('c', '<f8')])

Is there a np.astype syntax trick for this conversion?

2 Answers 2

1

Input for 'rows' of structure arrays is tuples:

In [464]: np.array([tuple(string_list)],dtype=my_dtype)
Out[464]: 
array([(123, 45.0, 6.7)], 
      dtype=[('a', '<i4'), ('b', '<f4'), ('c', '<f8')])

Another useful trick is to create an empty array of the required dtype, and fill in fields, one at a time. Or fill row by row with tuples, or multiple rows with a list of tuples.

Sign up to request clarification or add additional context in comments.

Comments

1

EDIT see @hpaulj answer. List has to be converted to tuple and list generates error.

with me this works, is that what you want?

string_list = ('123', '45.', '6.7')
b = np.array([string_list], dtype=[('a', '<i4'), ('b', '<f4'), ('c', '<f8')])

numpy version 1.8.2

1 Comment

Yes, the tuple conversion is all I was missing. Thanks!

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.