Reputation: 389
I have some arrays of numbers that are rounded to 2 digits, xx.xx (decimals=2, using np.around), that I would like to save to a text document for human reading. I would like to change these 'number' arrays to arrays of strings, so that I can combine them with other arrays of strings (row and column headers) and use numpy.savetxt in order to save my data in a readable way to a text document. How can I change my arrays of 'numbers' to arrays of strings? (I believe the numbers are rounded floats, which should still be float, not sure how to check though)
A=np.array([57/13, 7/5, 6/8])
which yields array([4.384615384615385, 1.4, 0.75 ])
B=A.astype('|S4' )
yields array([b'4.38',b'1.4', b'0.75]). The b's remain when I save to txt.
np.savetxt('my_file.txt', B, fmt="%s)
How do I get rid of the b's?
I know that they talk about the b's here What does the 'b' character do in front of a string literal?, but I don't see how to get rid of it.
Using .astype is not a requirement, just seemed like a good way to do it.
Upvotes: 1
Views: 287
Reputation: 284642
In your specific case, it's best to use np.savetxt(fname, data, fmt='%0.2f')
, where data
is your original floating point array.
The fmt
specifier is a sprintf-style format string. %0.2f
specifies numbers will be displayed as floats (f
-- as opposed to scientific notation) and formatted with as many characters as necessary to the left of the decimal point (the 0
) and 2 characters to the right of the decimal point.
For example:
import numpy as np
a = np.array([57./13, 7./5, 6./8])
np.savetxt('out.txt', a, fmt='%0.2f')
And the resulting out.txt
file will look like:
4.38
1.40
0.75
Upvotes: 1