I have been trying to use the savetxt
function in numpy. The problem I am running into is that even thought I define my variables accordingly, i.e. int() or double(), the text file i am getting out has floats in them. How can I change that?
Input is as follows: pNoise=[int(i), around(pNoise[0], decimals=3), around(pNoise[1], decimals=3), around(pNoise[2], decimals=3)]
savetxt line is as follows: savetxt(noutF, pNoisetot)
What I expect is: 0 1.567 8.865
instead I get 0.000000000000000000e+00 1.015909999999999940e+02 2.600000000000000089e-01
fmtstr or sequence of strs, optional. A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d – %10.5f', in which case delimiter is ignored. For complex X, the legal options for fmt are: a single specifier, fmt='%. 4e', resulting in numbers formatted like ' (%s+%sj)' % (fmt, fmt)
Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.
You can define how the output has to be formatted with the fmt
parameter of np.savetxt
, e.g.:
for floats rounded to five decimals:
np.savetxt("file.txt", output, fmt='%10.5f', delimiter='\t')
for integers:
np.savetxt("file.txt", output, fmt='%i', delimiter='\t')
Here you can find more information about the possibilities of fmt
:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
In case you want to specify the number of decimals in the float the
np.savetxt("file.txt", output, fmt='%10.5f', delimiter='\t')
7 decimals in this case
np.savetxt("file.txt", output, fmt='%10.7f', delimiter='\t')
Basically, fmt = %10.Yf' where Y specifies the number of decs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With