I'm curious, whether there is any way to print formatted numpy.arrays, e.g., in the way similar to this:
x = 1.23456
print '%.3f' % x
If I want to print the numpy.array of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for low-dimensional arrays. However, numpy.array apparently has to be printed as a string, i.e., with %s. Is there any solution for this purpose?
You can get a subset of the
np.set_printoptions
functionality from thenp.array_str
command, which applies only to a single print statement.http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html
For example:
Yet another option is to use the
decimal
module:I find that the usual float format {:9.5f} works properly -- suppressing small-value e-notations -- when displaying a list or an array using a loop. But that format sometimes fails to suppress its e-notation when a formatter has several items in a single print statement. For example:
My results show the bug in cases 4, 5, and 6:
I have no explanation for this, and therefore I always use a loop for floating output of multiple values.
You can use
set_printoptions
to set the precision of the output:And
suppress
suppresses the use of scientific notation for small numbers:See the docs for set_printoptions for other options.
To apply print options locally, using NumPy 1.15.0 or later, you could use the numpy.printoptions context manager. For example, inside the
with-suite
precision=3
andsuppress=True
are set:But outside the
with-suite
the print options are back to default settings:If you are using an earlier version of NumPy, you can create the context manager yourself. For example,
To prevent zeros from being stripped from the end of floats:
np.set_printoptions
now has aformatter
parameter which allows you to specify a format function for each type.which prints
instead of
The numpy arrays have the method
round(precision)
which return a new numpy array with elements rounded accordingly.The gem that makes it all too easy to obtain the result as a string (in today's numpy versions) is hidden in denis answer:
np.array2string