Reputation: 387
I have a string like that:
'[[-1. ]
[ 4.5]
[ 0. ]]
[[ 8.]
[ 0.]
[ 6.]]
[[ 0. ]
[ 4. ]
[ 0.66666667]]'
and I want to convert into a NumPy array like this
array([[[-1. ],
[ 4.5 ],
[ 0. ]],
[[ 8. ],
[ 0. ],
[ 6. ]],
[[ 0. ],
[ 4. ],
[ 0.66666667]]])
i try this code but didn't gat my answer
np.array(list(string.replace(']','],')))
Upvotes: 0
Views: 871
Reputation: 16916
If you know the size before hand then
np.fromstring(
s.replace('[', '').replace(']','').replace('\n', ''),
dtype=float, sep=' ').reshape(3,3)
Testcase:
s = '''[[-1. ]
[ 4.5]
[ 0. ]]
[[ 8.]
[ 0.]
[ 6.]]
[[ 0. ]
[ 4. ]
[ 0.66666667]]'''
np.fromstring(
s.replace('[', '').replace(']','').replace('\n', ''),
dtype=float, sep=' ').reshape(3,3)
Output:
array([[-1. , 4.5 , 0. ],
[ 8. , 0. , 6. ],
[ 0. , 4. , 0.66666667]])
Upvotes: 1