I'm attempting to convert the string '[ 0. 0. 1.]' to a numpy array.
This is the code I've written but is more complicated that needs be ?
arr = []
s = '[ 0. 0. 1.]'
arr.append(int(s.split(" ")[1].replace("." , '')))
arr.append(int(s.split(" ")[3].replace("." , '')))
arr.append(int(s.split(" ")[5].replace("]" , '').replace("." , '')))
arr = np.array(arr)
print(arr)
print(type(arr))
print(type(arr[0]))
Above code prints :
[0 0 1]
<class 'numpy.ndarray'>
<class 'numpy.int64'>
Is there a cleaner method to convert string '[ 0. 0. 1.]' to numpy int array type ?
asked Jun 15, 2018 at 19:50
blue-sky
54.3k161 gold badges470 silver badges787 bronze badges
2 Answers 2
Numpy as can handle it much easier than all the answers:
s = '[ 0. 0. 1.]'
np.fromstring(s[1:-1],sep=' ').astype(int)
answered Jun 15, 2018 at 20:20
anishtain4
2,4102 gold badges18 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
IN:
import numpy as np
s = '[ 0. 0. 1.]'
out = np.array([int(i.replace('.','')) for i in s[s.find('[')+1:s.find(']')].split()])
print(type(out))
OUT:
<class 'numpy.ndarray'>
answered Jun 15, 2018 at 19:59
rahlf23
9,0494 gold badges31 silver badges57 bronze badges
Comments
lang-py
np.array(s[1:-1].split(), float).astype(int)np.matrix(s).A1.astype(int)np.matrix(s[1:-1]).A1.astype(int)