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

1

1 Answer 1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.