Reputation: 7465
i need to write a couple of numpy floats to a csv-file which has additional string content. therefore i dont use savetxt etc. with numpy.set_printoptions() i can only define the print behaviour, but not the str() behaviour. i know that i miss something and it cant be that hard, but i dont find a reasonable answer on the interwebs. maybe someone can point me in the right direction. heres some example code:
In [1]: import numpy as np
In [2]: foo = np.array([1.22334])
In [3]: foo
Out[3]: array([ 1.22334])
In [4]: foo[0]
Out[4]: 1.2233400000000001
In [5]: str(foo[0])
Out[5]: '1.22334'
In [6]: np.set_printoptions(precision=3)
In [7]: foo
Out[7]: array([ 1.223])
In [8]: foo[0]
Out[8]: 1.2233400000000001
In [9]: str(foo[0])
Out[9]: '1.22334'
How do i convert np.float to a nicely formatted string, which i can feed to file.write()?
kind regards,
fookatchu
Upvotes: 19
Views: 44602
Reputation: 43762
Numpy 1.14 and later have format_float_positional
and format_float_scientific
functions to format a floating-point scalar as a decimal string in positional or scientific notation, with control over rounding, trimming and padding. These functions offer much more control to the formatting than conventional Python string formatters.
import numpy as np
x = np.float64('1.2345678')
print(np.format_float_positional(x)) # 1.2345678
print(np.format_float_positional(x, precision=3)) # 1.235
print(np.format_float_positional(np.float16(x))) # 1.234
print(np.format_float_positional(np.float16(x), unique=False, precision=8)) # 1.23437500
y = x / 1e8
print(np.format_float_scientific(y)) # 1.2345678e-08
print(np.format_float_scientific(y, precision=3, exp_digits=1)) # 1.235e-8
etc.
These advanced formatters are based on the Dragon4 algorithm; see Ryan Juckett's Printing Floating-Point Numbers to read more on the subject.
Upvotes: 7
Reputation: 14888
You could use normal String formating, see: http://docs.python.org/library/string.html#formatspec
Example:
print '{:.2f}'.format(0.1234) # '0.12'
print '{:.2e}'.format(0.1234) # '1.23e-01'
Upvotes: 12
Reputation: 316
Also you can do:
precision = 2
str(np.round(foo[0], precision))
It had some advantages for me over the ('%.2f' % x) when I needed to do string a str(np.log(0.0)) which is neatly treated to "-inf" by numpy so you don't have to bother here.
Upvotes: 0
Reputation: 613612
You can just use standard string formatting:
>>> x = 1.2345678
>>> '%.2f' % x
'1.23'
Upvotes: 18