Skip to content
Advertisement

adding a python string with a numpy array

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?

Advertisement

Answer

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])
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement