How do I print formatted NumPy arrays in a way similar to this:
x = 1.23456
print('%.3f' % x)
If I want to print the numpy.ndarray
of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for low-dimensional arrays. However, numpy.ndarray
apparently has to be printed as a string, i.e., with %s
. Is there a solution for this?
Best Answer
Use
numpy.set_printoptions
to set the precision of the output:And
suppress
suppresses the use of scientific notation for small numbers:To apply print options locally, using NumPy 1.15.0 or later, you could use the
numpy.printoptions
context manager. For example, inside thewith-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