4

I want to save a 3D binary array in .txt file or .csv file on python and import it onto mathematica.

I googled and I found a lot of answers, I try this:

import numpy as np
a=np.zeros((2,3,4))
a[0,0,0]=10
cPickle.dump( a, open( "matrix.txt", "wb" ) )

In mathematica I have used the Import["matrix.txt","Data"] and I did not get what I expect

IN[]:Import["matrix.txt", "Data"]

  Out[]:{{"cnumpy.core.multiarray"}, {"_reconstruct"}, {"p1"}, {"(cnumpy"}, \
    {"ndarray"}, {"p2"}, {"(I0"}, {"tS'b'"}, {"tRp3"}, {"(I1"}, {"(I2"}, \
    {"I3"}, {"I4"}, {"tcnumpy"}, {"dtype"}, {"p4"}, {"(S'f8'"}, {"I0"}, \
    {"I1"}, {"tRp5"}, {"(I3"}, {"S'<'"}, {"NNNI-1"}, {"I-1"}, {"I0"}, \
    {"tbI00"}, \
    {"S'\\x00\\x00\\x00\\x00\\x00\\x00$@\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\
    x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'"}, {"tb."}}
2
  • Um, Can you define what you were excepting? Commented Dec 16, 2015 at 6:21
  • @OrkunKoçyiğit, I have to get the value of the saved matrix! Commented Dec 16, 2015 at 6:25

1 Answer 1

7

The trick is to flatten the array as a 2D-array :

import numpy as np
a=np.zeros((2,3,4))
a[0,0,0]=10
b=a.reshape(1,24)

np.savetxt("/matrix.CSV",b,delimiter=',')

and then convert it in 3D in Mathematica after importing, we can use:

 file=Import["matrix.CSV","Data"]
 matrix=ArrayReshape[file, {2, 3, 4}]
Sign up to request clarification or add additional context in comments.

1 Comment

Congratulations for answering your own question and thanks for having posted it !

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.