Can numpy.savetxt be used on N-dimensional ndarrays with N>2? Can numpy.savetxt be used on N-dimensional ndarrays with N>2? numpy numpy

Can numpy.savetxt be used on N-dimensional ndarrays with N>2?


If you look at the source code for numpy.savetxt you'll find

    for row in X:        fh.write(asbytes(format % tuple(row) + newline))

so numpy.savetxt will only work for 1- or 2D-arrays.

For interoperability, you could use JSON if you have enough memory to convert the numpy array to a list:

import jsonimport numpy as npa = np.arange(24).reshape(-1, 2, 3, 4).astype('float')a[0,0,0,0] = np.nanwith open('/tmp/out', 'w') as f:    json.dump(a.tolist(), f, allow_nan = True)

yields

[[[[NaN, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], [8.0, 9.0, 10.0, 11.0]], [[12.0, 13.0, 14.0, 15.0], [16.0, 17.0, 18.0, 19.0], [20.0, 21.0, 22.0, 23.0]]]]


A different approach is to save the array as a simple list of numbers (the flat version of the array) and save along it the information about its shape.

The problem about multidimensional arrays is that it's not that simple to move them from program to program even in text format.

you can do something like this:

myarray = rand(5,5,5)name = 'myarray'+myarray.shape+'.txt'np.savetxt(name,myarray.flatten())

and use the information on the size inclued in the filename to restore the initial shape