2

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 ?

blue-sky
  • 49,326
  • 140
  • 393
  • 691

2 Answers2

6

Numpy as can handle it much easier than all the answers:

s = '[ 0.  0.  1.]'
np.fromstring(s[1:-1],sep=' ').astype(int)
anishtain4
  • 2,042
  • 1
  • 16
  • 19
0

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'>
rahlf23
  • 8,613
  • 3
  • 19
  • 49