Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

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.

1 Answer

0 votes
by (16.8k points)

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'

Related questions

0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Sep 27, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...