Search code examples
pythonarraysstringnumpywritefile

numpy array2string applied on huge array, skips central values, ( ... in the middle )


I have array of size (3, 3, 19, 19), which I applied flatten to get array of size 3249.

I had to write these values to file along with some other data, so I did following to get the array in string.

np.array2string(arr.flatten(), separator=', ', suppress_small=False)

However when I checked the content of the files after write, I noticed that I have ,... , in the middle of the array as following

[ 0.09720755, -0.1221265 , 0.08671697, ..., 0.01460444, 0.02018792, 0.11455765]

How can I get string of array with all the elements, so I can potentially get all data to a file?


Solution

  • As far as I understand array2string, it's just for returning a "nice" string representation of the array.

    numpy.ndarray.tofile might be a better option for your purposes - https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html. It should write the full contents of the array to the given file.

    with open("test.bin", "wb") as f:
        arr.flatten().tofile(f)
    

    And you can of course read it back with numpy.fromfile - https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html.

    with open("test.bin", "rb") as f:
        arr = numpy.fromfile(f)