1
$\begingroup$

Quick question, can anyone advise on an efficient way to convert complex arrays with complex part denoted '${I}$' in Mathematica to '$j$' (as used in Python) and curly brackets '{}' replaced with '[]' (as used in Python). I intend to then export the array as a csv. file and subsequently import it from Python.

Thanks for any assistance.

$\endgroup$
1
  • 1
    $\begingroup$ Convert the data to "String" and then use StringReplace. $\endgroup$ Jun 2, 2021 at 11:48

1 Answer 1

4
$\begingroup$

Probably better than going through CSV is to use "PythonExpression" as an exporting format, e.g.

ExportString[{1+2I,3+4I},"PythonExpression"]
(*"[Complex(1,2), Complex(3,4)]"*)

EDIT: Python seems to expect complex numbers defined through complex(real,imag) and not Complex(real,imag), so the full workflow would be:

  • In Mathematica
Export["data.txt",{1+2I,3+4I},"PythonExpression"]
  • In Python
with open("data.txt","r") as datafile:
    data = eval(datafile.read().lower())

I haven't really tested the efficiency of this approach, but unless that's a concern this technique seems rather convenient.

$\endgroup$
3
  • $\begingroup$ Thanks for your response. If you aren't using CSV, how do you access the array through Python? Is a special Python configuration required? $\endgroup$
    – John Doe
    Jun 2, 2021 at 13:48
  • $\begingroup$ I'd expect eval to work on the python side, so no special configuration required... but somehow Mathematica is exporting "Complex(real,imag)" when Python expects "complex(real,imag)"... so I've edited my answer accordingly $\endgroup$ Jun 2, 2021 at 14:07
  • $\begingroup$ Seems to work well on my side. Thanks, much appreciated. $\endgroup$
    – John Doe
    Jun 2, 2021 at 14:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.