0

For long and tedious reasons, I have lots of arrays that are stored as strings:

tmp = '[[1.0, 3.0, 0.4]\n [3.0, 4.0, -1.0]\n [3.0, 4.0, 0.1]\n [3.0, 4.0, 0.2]]'

Now I obviously do not want my arrays as long strings, I want them as proper numpy arrays so I can use them. Consequently, what is a good way to convert the above to:

tmp_np = np.array([[1.0, 3.0, 0.4]
                   [3.0, 4.0, -1.0]
                   [3.0, 4.0, 0.1]
                   [3.0, 4.0, 0.2]])

such that I can do simple things like tmp_np.shape = (4,3) or simple indexing tmp_np[0,:] = [1.0, 3.0, 0.4] etc.

Thanks

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Astrid
  • 1,846
  • 4
  • 26
  • 48
  • Have you seen https://stackoverflow.com/questions/20200353/reading-data-into-numpy-array-from-text-file?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa and a lot of other documentations regard this problem in Internet? – Mazdak Jun 07 '18 at 13:56

1 Answers1

1

You can use ast.literal_eval, if you replace your \n characters with ,:

temp_np = np.array(ast.literal_eval(tmp.replace('\n', ',')))

Returns:

>>> tmp_np
array([[ 1. ,  3. ,  0.4],
       [ 3. ,  4. , -1. ],
       [ 3. ,  4. ,  0.1],
       [ 3. ,  4. ,  0.2]])
sacuL
  • 49,704
  • 8
  • 81
  • 106