mesut_comak
mesut_comak

Reputation: 27

how to convert lists in string in numpy array to a numpy array

I have this numpy array ['[-30,30]' '[-30,30]' '[-30,30]' '[-30,30]'] But I would like to convert it into [[-30,30] [-30,30] [-30,30] [-30,30]]

How can I do that?

Thanks in advance!

Upvotes: 1

Views: 192

Answers (1)

I'mahdi
I'mahdi

Reputation: 24049

You can use ast.literal_eval like below:

>>> import ast
>>> lst = np.array(['[-30,30]','[-30,30]','[-30,30]', '[-30,30]'])

>>> type(lst[0])
numpy.str_

>>> type(ast.literal_eval(lst[0]))
list

>>> np.array(list(map(ast.literal_eval, lst)))
array([[-30,  30],
       [-30,  30],
       [-30,  30],
       [-30,  30]])

Upvotes: 1

Related Questions