I want to have a simple method to export a list of matrix from mathematica to python.

Consider the following code:

Mathematica :

test = Table[{{i, i^2}, {1, 2*i}}, {i, 1, 10}]
Export["test.CSV", test]

Python :

from numpy import genfromtxt
test=genfromtxt('test.csv', delimiter=',')

It returns me: [nan nan nan nan] on python side.

I tried to replace the list "test" on the mathematica side by


where this function is defined here (I saw it on another post, to be fair I'm not sure to totally understand what it does excepted it should replace the character to make it readable on python).

pyList[myList_] := 
   ToString@InputForm@myList, {"}, {" -> "],\n [", "{" -> "[", 
    "," -> ",", "}" -> "]"}]

What is the Simplest way to transfer a list from mathematica to python ?

Also, bonus question:

Actually I will have more than one list to transfer: some will be list of matrices, other will just be list of number. I would like to be able to transfer them as well.

  • $\begingroup$ You are really asking how to read a csv file in python... here's one way: pythonspot.com/reading-csv-files-in-python $\endgroup$ – bill s Jul 4 '19 at 16:33
  • $\begingroup$ @bills I'm asking how to make consistant the export from mathematica to the import in python. To export in the simplest way list from mathematica to python $\endgroup$ – StarBucK Jul 4 '19 at 16:47
  • 2
    $\begingroup$ Better use the hdf5 format for a cross-platform exchange of tensor data. $\endgroup$ – Henrik Schumacher Jul 4 '19 at 17:05
  • $\begingroup$ @HenrikSchumacher thank you very much. Indeed it is very simple through this format ! $\endgroup$ – StarBucK Jul 5 '19 at 13:25
  • 1
    $\begingroup$ @StarBucK You're welcome! (Btw. hdf5 is also much more efficient than CSV because it is a binary format. There are some peculiarities with complex-valued tensors, though, because real and imaginary parts have to be stored separately.) $\endgroup$ – Henrik Schumacher Jul 5 '19 at 13:29

Your Answer

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

Browse other questions tagged or ask your own question.