-4

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.

La_haine
  • 339
  • 1
  • 6
  • 18
  • 3
    "It's not working" is not a good description. Please include what you have tried and _why_ it didn't work including a full error message. Ideally you should create a [mcve]. – DavidG May 14 '19 at 09:21
  • I tried with np.fromstring(my_string), it returns this kind of error: "ValueError: string size must be a multiple of element size". – La_haine May 14 '19 at 09:22
  • Couldn't reproduce. I'm on Python 3.7(.0) but I'm getting a different output: no error, a deprecation warning about binary mode, and a numpy array. – TrebledJ May 14 '19 at 09:32
  • 1
    Is it normal that the elements of the first sublist are separated with comma whereas the others by space ? – Alexandre B. May 14 '19 at 09:33
  • You may find tbe second comment here useful... https://stackoverflow.com/q/38886641/8008686 – DougM May 14 '19 at 09:37
  • 1
    Possible duplicate of [convert string representation of array to numpy array in python](https://stackoverflow.com/questions/38886641/convert-string-representation-of-array-to-numpy-array-in-python) – DougM May 14 '19 at 09:37
  • @TrebledJ what kind of output did you get? I'm haveing this: array([7.11152197e-067, 2.38046558e-038, 8.94194746e+130, 2.51885231e-052, 1.73096317e-153, 1.56978741e+140]) – La_haine May 14 '19 at 09:42
  • 1
    Yep, I'm getting that too. It's probably trying to represent 0 due to a float64 type. Probably due to a parsing error (check the commas). If I replace the gaps with commas, I get a ValueError, as you did. – TrebledJ May 14 '19 at 09:47
  • 1
    Possible duplicate of [how to read numpy 2D array from string?](https://stackoverflow.com/questions/35612235/how-to-read-numpy-2d-array-from-string) – TrebledJ May 14 '19 at 09:48

1 Answers1

1

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' >
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40