7

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?

Brandon Lee
  • 695
  • 1
  • 10
  • 22
  • 2
    `array2string` is used by the array `print` to display a summary of the array. When it inserts `...` is determined by the `threshold`. Are you sure you want/need that format? It includes `[]` which make parsing harder. `.tofile` writes a flat list of numbers without those. – hpaulj Jul 02 '18 at 21:55
  • @hpaulj It is intentional so I need [] – Brandon Lee Jul 03 '18 at 16:36
  • If one does not exactly know, how many entries the array will have, one can set `threshold=np.inf` in `array2string`. – feli_x Nov 27 '21 at 17:43

1 Answers1

5

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)
Seabass
  • 372
  • 1
  • 6
  • I have tried this already but this is not an option because the program that will be using this file will not be python either. also the content of the file was not human readable – Brandon Lee Jul 03 '18 at 16:36
  • Please have a look at the `tofile` docs. You can supply the `sep` argument to `tofile`, which will cause it to output in text format. If you have additional constraints on the output then please update the question accordingly. – Seabass Jul 04 '18 at 08:25