2

I have a string

s = "[0. -0.002j,-0.002-0.002j,-0.003+0.j ],\n[0.01+0.j , 0.001-0.001j,-0. +0.0009j]]"

And I'd like to convet this to np.array. Using np.fromstring np.loadtxt and using JSON as an intermediate step all have problems with complex numbers (and it's even worse with comma separation.

This type of output is generated by np.array2string(x,separator=',').

What would be elegant/concise/canonical way of doing this conversion?


Initial missing bracket is a typo, keeping original statement of the question so that answers make more sense.

3
  • 1
    np.array(eval('[' + s.replace('\n',''))) Commented Dec 11, 2019 at 12:46
  • about missing bracket - copying typo, thanks! Commented Dec 11, 2019 at 12:50
  • 1
    Generating the string with repr(x.tolist()) would be safer. Better yet a pickle.dumps. Commented Dec 11, 2019 at 13:09

1 Answer 1

4

If you fix the missing leading bracket, you can treat this as a regular list with the ast built-in module:

>>> import ast
>>> s = "[[0. -0.002j,-0.002-0.002j,-0.003+0.j ],\n[0.01+0.j , 0.001-0.001j,-0. +0.0009j]]"
>>> ast.literal_eval(s)
[[-0.002j, (-0.002-0.002j), (-0.003+0j)], [(0.01+0j), (0.001-0.001j), 0.0009j]]
>>> import numpy as np
>>> np.array(ast.literal_eval(s))
array([[ 0.   -0.002j , -0.002-0.002j , -0.003+0.j    ],
       [ 0.01 +0.j    ,  0.001-0.001j ,  0.   +0.0009j]])
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.