-1

I am loading some external data that looks like:

[[1 0 0][1 1 1][0 1 1]]

(no commas) into my code that requires arrays to run. I would like the code to look like:

np.array([[1 0 0],[1 1 1],[0 1 1]])

I'm not sure how to covert this to an array.

I've tried treating it as a list but that doesn't work.

martineau
  • 119,623
  • 25
  • 170
  • 301
Bobert
  • 31
  • 4
  • What format exactly is the external data in? A string? – martineau Jun 19 '19 at 17:29
  • This is a malformed array of lists np.array([[1 0 0],[1 1 1],[0 1 1]]). It should be np.array([[1, 0, 0],[1, 1, 1],[0, 1, 1]]). Do you agree? – jose_bacoy Jun 19 '19 at 17:33
  • That's what the print of numpy looks like. It's not intended for saving or conversion back to an array. If the array is large enough it will contain ellipsis. – hpaulj Jun 19 '19 at 17:51

1 Answers1

0

I will use ast and replace some chars with comma.

import ast
txt = "[[1 0 0][1 1 1][0 1 1]]".replace('][', '],[').replace(' ', ',')
np.array(ast.literal_eval(txt))

Result:
array([[1, 0, 0],[1, 1, 1],[0, 1, 1]])

Reference: https://docs.python.org/2/library/ast.html

jose_bacoy
  • 12,227
  • 1
  • 20
  • 38