-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.

9
  • 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 minimal reproducible example. Commented May 14, 2019 at 9:21
  • 1
    Is it normal that the elements of the first sublist are separated with comma whereas the others by space ? Commented May 14, 2019 at 9:33
  • 1
    Possible duplicate of convert string representation of array to numpy array in python Commented May 14, 2019 at 9:37
  • 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. Commented May 14, 2019 at 9:47
  • 1
    Possible duplicate of how to read numpy 2D array from string? Commented May 14, 2019 at 9:48

1 Answer 1

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' >
Sign up to request clarification or add additional context in comments.

1 Comment

This is the kind of output I wanted. Many thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.