Home > Net >  how to convert lists in string in numpy array to a numpy array
how to convert lists in string in numpy array to a numpy array

Time:04-08

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!

CodePudding user response:

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]])
  • Related