9

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?

3
  • 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. Commented Jul 2, 2018 at 21:55
  • @hpaulj It is intentional so I need [] Commented Jul 3, 2018 at 16:36
  • If one does not exactly know, how many entries the array will have, one can set threshold=np.inf in array2string. Commented Nov 27, 2021 at 17:43

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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
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.
1

Try the following: numpy.set_printoptions(threshold=np.inf)

It tells NumPy to display all the elements of an array without cutting any out, no matter how large the array is. Normally, if you print a large array, NumPy shortens the output with ... to avoid overwhelming you with too many numbers. By setting the threshold to infinity (np.inf), you remove that limit, allowing the entire array to be shown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.