3

I have a string as follows:

>>> a
'0 911 872.9 354.9 901.9 395.0 904.6 414.0 903.8 400.5'

Now I wish to convert it into an array:

>>> b
array([   0. ,  911. ,  872.9,  354.9,  901.9,  395. ,  904.6,  414. ,
        903.8,  400.5])

What is the most Pythonic way of doing this?

1
  • 1
    @BurhadKhalid: Are you sure, OP meant numpy and not array Commented Oct 3, 2013 at 7:32

4 Answers 4

10

Use numpy.fromstring:

import numpy as np
np.fromstring(a, dtype=float, sep=' ')

Demo:

>>> np.fromstring('0 911 872.9 354.9 901.9 395.0 904.6 414.0 903.8 400.5', dtype=float, sep=' ')
array([   0. ,  911. ,  872.9,  354.9,  901.9,  395. ,  904.6,  414. ,  903.8,  400.5])  
Sign up to request clarification or add additional context in comments.

Comments

3

The simplest would be to split the string based on white-space followed by mapping the string data to float. You can use imap, if you would not want to create throw away intermediate strings. Also I would suggest to create array's of doubles to reduce precision errors.

Demo

>>> from array import array
>>> from itertools import imap
>>> array('d', imap(float, a.split()))
array('d', [0.0, 911.0, 872.9, 354.9, 901.9, 395.0, 904.6, 414.0, 903.8, 400.5])
>>> 

1 Comment

The difference in the representation of the resulting array indicates to me that the OP probably means numpy arrays. This is a useful answer too though.
3

b = array([float(x) for x in a.split()])

Comments

0
b = map(lambda x: float(x), x.split())

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.