I'm using Python 3.7 and I have this kind of string:
"[[0,1,32]\n [3 8 84]\n [57 85 85]\n [57 85 85]\n]"
I would like to transform this in a numpy array. How can I do?
I already tried with the numpy method fromstring(), but it's not working.
I'm using Python 3.7 and I have this kind of string:
"[[0,1,32]\n [3 8 84]\n [57 85 85]\n [57 85 85]\n]"
I would like to transform this in a numpy array. How can I do?
I already tried with the numpy method fromstring(), but it's not working.
Applying the link provide by @DMellon in comments:
# Import modules
import ast
import re
text = "[[0,1,32]\n [3 8 84]\n [57 85 85]\n [57 85 85]\n]"
# Replace comma from first sublist to list
text = text.replace(",", " ")
# Remove all `\n`
text = text.replace('\n', '')
# Add ','
xs = re.sub('\s+', ',', text)
# Convert to np.ndarray
a = np.array(ast.literal_eval(xs))
print(a)
# [[0 1 32]
# [3 8 84]
# [57 85 85]
# [57 85 85]]
print(type(a))
# <class 'numpy.ndarray' >