Just a short question, I am trying to import a complex array (matrix) from Python to Mathematica by first writing to a csv. file. When I Import the csv. array to Mathematica it is in a form (matrix elements are wrapped in round brackets with imaginary part denoted with Python imaginary part symbol 'j') that is not compatible with Mathematica as indicated by the code example (2x2 matrix) below: The matrix $A$ that I am importing as an example is: \begin{pmatrix} i &2 \\ 3 & 4 \end{pmatrix}

A = Import["C:\\Users\\JohnDoe\\Documents\\PycharmProjects\\pythonProject\\foo.csv", "Data"]

where the output of imported array A in Mathematica is:

{(3.00000000000000000e+00+0.00000000000000000e+00j), (4.00000000000000000e+00+0.00000000000000000e+00j)}}

Can anyone advise on how to process the array after importing such that it is in a standard Mathematica form without brackets (and standard Mathematica imaginary part)?

Thanks for any assistance.


In Python

To reproduce the same result, I use the following code in python:

import numpy

a = numpy.asarray([ [1j,2+0j], [3+0j,4+0j] ])

In python when you want to export the array in CSV file with Numpy, use fmt to change the default formatting (i stands for integer, see here for more information):

numpy.savetxt("foo.csv", a, delimiter=",", fmt="%i")

Now you will have a file containing the following data:

File: foo.csv

 (0+1j), (2+0j)
 (3+0j), (4+0j)

In Mathematica

First import the file:

data = Import["C:\\foo.csv"];

then define a function to replace j with I and remove the paranthesis and interpret that as a complex number:

toComplex[s_String] := 
  StringReplace[s, {"j" -> "I", "(" -> "", ")" -> ""}]]

Now apply the function to every element you'd imported:

Map[toComplex, data, {2}]

(*Out: {{I, 2}, {3, 4}} *)

Another Solution

If possible, you can use ExternalEvaluate["Python", ... ] to convert to Mathematica built-in data types directly:

a = ExternalEvaluate["Python", "[[1j,2+0j],[3+0j,4+0j]]"]

(*Out: {{0. + 1. I, 2. + 0. I}, {3. + 0. I, 4. + 0. I}} *)

Update - Mathematica to Python


data = {{0. + 1. I, 2. + 0. I}, {3. + 0. I, 4. + 0. I}};

Export["C:\\bar.csv", StringReplace[ExportString[data, "CSV"], "*I" -> "j"], "Text"]
File: bar.csv



With Numpy:

import numpy as np
result1= np.vectorize(complex)(np.genfromtxt('bar.csv', delimiter=',',dtype='str'))

# Out: [[0.+1.j 2.+0.j]
#       [3.+0.j 4.+0.j]]

# Out: 2.0

Pure Python:

result2 = []
with open('bar.csv','r') as f:
    for line in f.readlines():
        result2.append([complex(i) for i in line.strip().split(delimiter)])

# Out: [[1j, (2+0j)], [(3+0j), (4+0j)]]

# Out: 2.0

Update 2 - Small numbers


data = RandomComplex[{0, 1 + 1 I}, {2, 2}]*10^-8;

 StringReplace[ExportString[data, "CSV"], {"*^" -> "e", "*I" -> "j", 
   "I" -> "j"}], "Text"]

Re[data[[1, 1]]] // InputForm
(*Out: 8.766084925741931*^-9 *)


import numpy as np

result3=np.vectorize(complex)(np.genfromtxt(r"C:\imag2.csv", delimiter=',',dtype='str'))

# Out: 8.766084925741931e-09
  • $\begingroup$ Please advise on how you would do the reverse, hence replace the complex $i$ in Mathematica with $j$ (in preparation for exporting to Python using a csv. file). $\endgroup$
    – John Doe
    Jun 2 at 11:30
  • 1
    $\begingroup$ @JohnDoe answer updated. $\endgroup$
    – Ben Izd
    Jun 5 at 6:28
  • $\begingroup$ How would you go about sending arrays (from Mathematica to Python) with floats and exponential coefficients on real and imaginary parts? For example A = {{0.55*10^-6 + 0. I, -0.55*10^-6 - 9.18*10^-7 I}, {-0.55*10^-6 - 2.49*10^-6 I, 0.55*10^-6 - 1.31*10^-6 I}} $\endgroup$
    – John Doe
    Jun 22 at 11:21
  • $\begingroup$ Hi for your info I posted as a new question. $\endgroup$
    – John Doe
    Jun 22 at 13:22
  • $\begingroup$ @JohnDoe For the sake of completeness, I updated the answer instead of posting it on your new question. $\endgroup$
    – Ben Izd
    Jun 22 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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