1

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!

9
  • What exactly is the input? Certainly not a numpy array. Here you have a single string embedded in a list Commented Apr 7, 2022 at 12:36
  • Input is ['[-30,30]' '[-30,30]' '[-30,30]' '[-30,30]'] ,it is a numpy array consist of strings and output should look like [[-30,30] [-30,30] [-30,30] [-30,30]] just a numpy array Commented Apr 7, 2022 at 12:38
  • So input is ['[-30,30][-30,30][-30,30][-30,30]']? 'a' 'b' in python is 'ab' Commented Apr 7, 2022 at 12:39
  • That's the same, run it in a python shell. Thus my question, your input is unclear. Do you then mean "['[-30,30]' '[-30,30]' '[-30,30]' '[-30,30]']"? Or ['[-30,30]', '[-30,30]', '[-30,30]', '[-30,30]']? Commented Apr 7, 2022 at 12:41
  • this is the input ['[-30,30]' '[-30,30]' '[-30,30]' '[-30,30]'] Commented Apr 7, 2022 at 12:44

1 Answer 1

1

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]])
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.