0

I am searching for the easiest way to save an array in a file. For this I would want to use numpy.savetxt but the problem is that my array is composed of n columns (the number depends on what i ant to do) and it contains complex elements (x+yj). I know how to save it if there is one column and real elements but I don't know how to do.

Does anybody have an idea?

3
  • Sorry I'm not allowed to comment but have you looked at stackoverflow.com/questions/3685265/…. yay that actually worked as a comment Commented Mar 14, 2012 at 18:10
  • I red it but there is not a very short answer. In fact I want to write something like 'numpy.savetext('myfile',myarray,fmt=???)'. Commented Mar 14, 2012 at 18:20
  • Have you tried the examples I gave? I ran them in the interpreter so I know they work. Does the output have to be human readable? Commented Mar 14, 2012 at 18:22

1 Answer 1

2

You could pickle them:

>>> A = np.array([[1,2],[3,4+2j]])
>>> pickle.dump(A, open("out.pkl", "wb"))
>>> pickle.load(open("out.pkl", "rb"))
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+2.j]])

However, it would be better to use numpy.save and numpy.load, they're designed for this and will use a lot less space.

>>> np.save("out.npy", A)
>>> np.load("out.npy")
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+2.j]])
Sign up to request clarification or add additional context in comments.

3 Comments

I already tried this and the answer is 'Casting complex values to real discards the imaginary part fh.write(asbytes(format % tuple(row) + newline))'
numpy.savetxt gives that output, not numpy.save. The savetxt function produces human readable output, and it doesn't work for this.
+1 on numpy.save , if you're not going to use it outside of Python.

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.