Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to printing numpy array with 3 decimal places? [duplicate]

Tags:

python

numpy

How can I print numpy array with 3 decimal places? I tried array.round(3) but it keeps printing like this 6.000e-01. Is there an option to make it print like this: 6.000?

I got one solution as print ("%0.3f" % arr), but I want a global solution i.e. not doing that every time I want to check the array contents.

like image 457
Jack Twain Avatar asked Mar 06 '14 11:03

Jack Twain


People also ask

How do you change the precision of a NumPy array?

If you just want the same digits, you could use np. around() to round the results to some appropriate number of decimal places. However, by doing this you'll only reduce the precision of the result. If you actually want to compute the result more precisely, you could try using the np.


2 Answers

 np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)}) 

This will set numpy to use this lambda function for formatting every float it prints out.

other types you can define formatting for (from the docstring of the 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' 
like image 109
M4rtini Avatar answered Oct 07 '22 04:10

M4rtini


Actually what you need is np.set_printoptions(precision=3). There are a lot of helpful other parameters there.

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]] 
like image 20
Salvador Dali Avatar answered Oct 07 '22 04:10

Salvador Dali