Sometimes the printed numpy
array is provide to share the data such as this post. So far, I converted that manually. But the array in the post is too big to convert by hand.
I want to convert a string representation of a numpy
array back to an array. (Thanks, @LevLevitsky. I reference your expression.)
I tried this code
import numpy as np
print np.array([[0, 1], [2, 3]])
#[[0 1]
# [2 3]]
# the output is
output = '''[[0 1]
[2 3]]'''
import re
pat_ignore = re.compile(r'[\[\]]')
numbers = pat_ignore.sub('', output)
print np.array([map(float, line.split()) for line in numbers.splitlines()])
[[ 0. 1.]
[ 2. 3.]]
However, this could not retain the data type. Also if ndim > 3
, It does not work properly.
[[[0 1]
[2 3]]]
is interpreted as
[[ 0. 1.]
[ 2. 3.]]
You can use re
to treat the string and then create the array using eval()
:
import re
from ast import literal_eval
import numpy as np
a = """[[[ 0 1]
[ 2 3]]]"""
a = re.sub(r"([^[])\s+([^]])", r"\1, \2", a)
a = np.array(literal_eval(a))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With