1

I want to make '1 2 3' into a numpy [1, 2, 3]

I've tried

x = '1 2 3'
x = np.fromstring(x, dtype=int, sep=' ')

and it works, but is there any other way to do it? Maybe using np.array()? Thanks.

1
  • np.array('1 2 3'.split(),int). np.array expects a list, not a string. fromstring expects a string. Commented Oct 9, 2021 at 7:33

1 Answer 1

1

If you really want you could do np.array(x.split()), but the numpy.fromstring method will be faster.

Timing for np.fromstring on 1000 times x: 45.2 µs ± 4.29 µs

Timing for np.array: 329 µs ± 67.6 µs

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

1 Comment

np.array can convert to int without the previous map.

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.