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?

PanAkry
  • 183
  • 4
  • 9
  • Sorry I'm not allowed to comment but have you looked at http://stackoverflow.com/questions/3685265/how-to-write-a-multidimensional-array-to-a-text-file. yay that actually worked as a comment – Snesticle Mar 14 '12 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=???)'. – PanAkry Mar 14 '12 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? – strcat Mar 14 '12 at 18:22

1 Answers1

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]])
strcat
  • 5,376
  • 1
  • 27
  • 31
  • I already tried this and the answer is 'Casting complex values to real discards the imaginary part fh.write(asbytes(format % tuple(row) + newline))' – PanAkry Mar 14 '12 at 18:16
  • `numpy.savetxt` gives that output, not `numpy.save`. The `savetxt` function produces human readable output, and it doesn't work for this. – strcat Mar 14 '12 at 18:18
  • +1 on numpy.save , if you're not going to use it outside of Python. – rdchambers Mar 14 '12 at 19:40