1

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.

3
  • possible duplicate of Numpy converting array from float to strings Commented Jul 22, 2015 at 0:44
  • @Mark you can check np.char.array() Commented Jul 22, 2015 at 0:56
  • Is using astype a requirement for the problem? Commented Jul 22, 2015 at 1:10

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this is helpful; however my output looks like 4.381.400.75 (all in one line with no spaces).
@Mark - That's because it's a 1D array. If you'd like it to be a 2D column vector, save np.column_stack([your_data]) or your_data[:,None].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.