4

When I call:

np.fromstring('3 3 3 0', sep=' ')

it returns

array([ 3.,  3.,  3.,  0.])

Since by default, sep='', I would expect the following call to return the same result:

np.fromstring('3330')

However it raises

ValueError: string size must be a multiple of element size

Why is this? What's the most pythonic way of getting array([ 3., 3., 3., 0.]) from '3330'?

1
  • 1
    The documentation says this about the sep keyword: "If not provided or, equivalently, the empty string, the data will be interpreted as binary data." Commented Dec 18, 2014 at 20:17

2 Answers 2

6

You could use np.fromiter:

In [11]: np.fromiter('3300', dtype=np.float64)
Out[11]: array([ 3.,  3.,  0.,  0.])

In [12]: np.fromiter('3300', dtype=np.float64, count=4)  # count=len(..)
Out[12]: array([ 3.,  3.,  0.,  0.])
Sign up to request clarification or add additional context in comments.

Comments

0

list('3330') turns the string into a 4 element list of chars; with the correct dtype, np.array will convert those strings to numbers:

In [48]: np.array(list('3330'),dtype=float)
Out[48]: array([ 3.,  3.,  3.,  0.])

The fromiter solution is faster, but that's one more function to remember.

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.