Numpy.savetxt to keep string and float meanwhile and keep float precision
I wrote a python script,
import numpy a = 8.3 b = 8.29993191 c = abs(a - b) print c d = numpy.array(c) e = ['value'] f = numpy.vstack((e, d)) print f g = ['valuesssssssssssss'] h = numpy.vstack((g, d)) print h numpy.savetxt('2k.csv', f, '%s', delimiter = ',')
And here is the conclusion,
6.8090000001e-05
[['value']
['6.809']]
[['valuesssssssssssss']
['6.8090000001e-05']]
Apparently the precision of the float I want to save to the csv file depends on the length of the string, because I need to use '% s' to store the string and float at the same time.
How to solve this problem?
source to share
In this line:
f = numpy.vstack((e, d))
vstack
pushes type d
to type e
. You can check this by typing f.dtype
.
Instead, you should build f
like this
f = np.zeros(1,dtype=('|S5, float64'))
f[0] = e[0],d
Refer to the docs on structured arrays specifically for this point if you do not understand the above line.
f
You can choose a different format specifier during printing . With numbers 15
and scientific notation, you can go:
np.savetxt('2k.csv', f, fmt = ('%s','%.15e'),delimiter = ',')
The resulting file
# cat 2k.csv
value,6.809000000096432e-05
To store the number below the line, use a custom format for savetxt
:
np.savetxt('2k.csv', f, fmt = '%s\n%.15e')
which outputs:
# cat 2k.csv
value
6.809000000096432e-05
source to share