I have a string of numbers like this:
JavaScript
x
3
1
line
2
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'
3
I have a numpy array of numbers like this:
JavaScript
1
5
1
rpm
2
Out[3]:
3
array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
4
0., 0., 0., 0., 0., 0., 0., 0.])
5
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
.
JavaScript
1
6
1
import numpy as np
2
3
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'
4
res = np.fromstring(line, dtype=int, sep=',')
5
print(res)
6
Output:
JavaScript
1
3
1
array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2
0, 0])
3