Skip to content Skip to sidebar Skip to footer

Can Numpy.savetxt Be Used On N-dimensional Ndarrays With N>2?

I am trying to output a 4D numpy float array to a plaintext file using numpy.savetxt However numpy gives an error saying that a float argument is required when I try to pass this a

Solution 1:

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 json
import numpy as np
a = np.arange(24).reshape(-1, 2, 3, 4).astype('float')
a[0,0,0,0] = np.nan
withopen('/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]]]]

Solution 2:

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

Post a Comment for "Can Numpy.savetxt Be Used On N-dimensional Ndarrays With N>2?"