How to print a numpy array with 3 decimal places?

How can I print a numpy array with 3 decimal places? I tried array.round(3) , but it keeps printing as follows 6.000e-01 . Is there any way to do this as follows: 6.000 ?

I have one solution like print ("%0.3f" % arr) , but I want a global solution, that is, I do not do this every time I want to check the contents of the array.

+7
python numpy
source share
3 answers
  np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)}) 

This will set numpy to use this lambda function to format each float that it prints.

other types that you can define formatting for (from the docstring function)

  - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` - 'str' : all other strings Other keys that can be used to set a group of types at once are:: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'str' and 'numpystr' 
+10
source share

Actually you need np.set_printoptions(precision=3) . There are many other useful options .

For example:

 np.random.seed(seed=0) a = np.random.rand(3, 2) print a np.set_printoptions(precision=3) print a 

will show you the following:

 [[ 0.5488135 0.71518937] [ 0.60276338 0.54488318] [ 0.4236548 0.64589411]] [[ 0.549 0.715] [ 0.603 0.545] [ 0.424 0.646]] 
+7
source share

A simpler solution is to use numpy around.

 >>> randomArray = np.random.rand(2,2) >>> print(randomArray) array([[ 0.07562557, 0.01266064], [ 0.02759759, 0.05495717]]) >>> print(np.around(randomArray,3)) [[ 0.076 0.013] [ 0.028 0.055]] 
+4
source share

All Articles