dirtysocks45 dirtysocks45 - 1 month ago 13
Python Question

Use integer representation instead of floats when writing a numpy array to a text file

Currently I have the code:

numpy.savetxt("FILENAME.csv", Z, delimiter=",")


This produces
FILENAME.csv
that contains:

1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00
1.000000000000000000e+00


However, I want it to be:

1, 1, 1, 1, 1, 1, 1, 1


How do I modify my code to make these changes?

Note that
Z
is an
np array

wim wim
Answer Source

What you're seeing is the default format, fmt='%.18e'.

You may specify the keyword argument fmt to provide a format for integers:

numpy.savetxt("FILENAME.csv", Z, fmt='%d', delimiter=",")

To provide the values on one line, just reshape Z:

numpy.savetxt("FILENAME.csv", Z.reshape(1,-1), fmt='%d', delimiter=", ")