blue-sky
blue-sky

Reputation: 53786

Convert string array to numpy array

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 ?

Upvotes: 2

Views: 4183

Answers (2)

anishtain4
anishtain4

Reputation: 2402

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

s = '[ 0.  0.  1.]'
np.fromstring(s[1:-1],sep=' ').astype(int)

Upvotes: 6

rahlf23
rahlf23

Reputation: 9019

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

Upvotes: 0

Related Questions