I can convert a string representation of a list to a list with ast.literal_eval. Is there an equivalent for a numpy array?
x = arange(4)
xs = str(x)
xs
'[0 1 2 3]'
# how do I convert xs back to an array
Using ast.literal_eval(xs) raises a SyntaxError. I can do the string parsing if I need to, but I thought there might be a better solution.
reprthat can be used to reconstruct even a python list. You could doctor the string to recreate a list then create a numpy array from that e.g.numpy.array(ast.literal_eval(', '.join(xs.split(' '))))- Paul Rooneyast.literal_eval? If so, then the answer is no, you can't get a numpy array fromliteral_eval. From the python documentation ofast.literal_eval(node_or_string): "The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None." If what you really want is a convenient way to convert a numpy array to a string and then back to an array, please elaborate on that in the question. - Warren Weckesserast.literal_evalthat worked for numpy arrays, but didn't expect to useast.literal_eval. - jdmcbr