Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

savetxt How change the type from float64 to int or double

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

like image 207
madtowneast Avatar asked Mar 17 '11 23:03

madtowneast


People also ask

What is FMT in Python?

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)

How do I convert a Numpy array to text?

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.


2 Answers

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

like image 197
joris Avatar answered Sep 23 '22 05:09

joris


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.

like image 26
jakue89 Avatar answered Sep 25 '22 05:09

jakue89