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 ?

5
  • depends on how flexible you want to be. np.array(s[1:-1].split(), float).astype(int) Commented Jun 15, 2018 at 19:58
  • or even np.matrix(s).A1.astype(int) Commented Jun 15, 2018 at 20:03
  • @PaulPanzer s = '[ 0. 0. 1.]' np.matrix(s) returns 'TypeError: Invalid data string supplied: [' Commented Jun 15, 2018 at 20:06
  • Strange, it works for me. Which versions are you on? Commented Jun 15, 2018 at 20:15
  • Looks like it changed sometime during 1.13.x. So if you are 1.12 or less you'll have to do np.matrix(s[1:-1]).A1.astype(int) Commented Jun 15, 2018 at 20:54

2 Answers 2

6

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

s = '[ 0.  0.  1.]'
np.fromstring(s[1:-1],sep=' ').astype(int)
Sign up to request clarification or add additional context in comments.

Comments

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'>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.