0

I have a string of numbers like this:

line
Out[2]: '1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'

I have a numpy array of numbers like this:

rpm
Out[3]:
array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0.])

I'd like to add the line of numbers in the string to the numbers in the array, and keep the result in the array.

Is there a simple/elegant way to do this using numpy or python?

2
  • are these two array of difference shape? Commented Oct 6, 2022 at 19:36
  • np.array(line.split(','),int) also works - giving array a list of strings and telling it to interpret them as ints. Commented Oct 6, 2022 at 21:43

1 Answer 1

1

You can use numpy.fromstring.

import numpy as np

line = '1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'
res = np.fromstring(line, dtype=int, sep=',')
print(res)

Output:

array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0])
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, this works well. I was looking at map and where and other functions, and glad to see there is a fromstring() function.

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.