In another question, other users offered some help if I could supply the array I was having trouble with. However, I even fail at a basic I/O task, such as writing an array to a file.
Can anyone explain what kind of loop I would need to write a 4x11x14 numpy array to file?
This array consist of four 11 x 14 arrays, so I should format it with a nice newline, to make the reading of the file easier on others.
Edit: So I’ve tried the numpy.savetxt function. Strangely, it gives the following error:
TypeError: float argument required, not numpy.ndarray
I assume that this is because the function doesn’t work with multidimensional arrays? Any solutions as I would like them within one file?
If you want to write it to disk so that it will be easy to read back in as a numpy array, look into
numpy.save. Pickling it will work fine, as well, but it’s less efficient for large arrays (which yours isn’t, so either is perfectly fine).If you want it to be human readable, look into
numpy.savetxt.Edit: So, it seems like
savetxtisn’t quite as great an option for arrays with >2 dimensions… But just to draw everything out to it’s full conclusion:I just realized that
numpy.savetxtchokes on ndarrays with more than 2 dimensions… This is probably by design, as there’s no inherently defined way to indicate additional dimensions in a text file.E.g. This (a 2D array) works fine
While the same thing would fail (with a rather uninformative error:
TypeError: float argument required, not numpy.ndarray) for a 3D array:One workaround is just to break the 3D (or greater) array into 2D slices. E.g.
However, our goal is to be clearly human readable, while still being easily read back in with
numpy.loadtxt. Therefore, we can be a bit more verbose, and differentiate the slices using commented out lines. By default,numpy.loadtxtwill ignore any lines that start with#(or whichever character is specified by thecommentskwarg). (This looks more verbose than it actually is…)This yields:
Reading it back in is very easy, as long as we know the shape of the original array. We can just do
numpy.loadtxt('test.txt').reshape((4,5,10)). As an example (You can do this in one line, I’m just being verbose to clarify things):