Home > Backend Development > Python Tutorial > How Can I Pretty-Print NumPy Arrays with Controlled Precision and Scientific Notation Suppression?

How Can I Pretty-Print NumPy Arrays with Controlled Precision and Scientific Notation Suppression?

Patricia Arquette
Release: 2024-12-08 01:14:11
Original
606 people have browsed it

How Can I Pretty-Print NumPy Arrays with Controlled Precision and Scientific Notation Suppression?

Pretty-Print NumPy Arrays with Precision and Suppression of Scientific Notation

When working with NumPy arrays of浮点数s, it's common to encounter readability issues due to extensive decimal places and the use of scientific notation. To address this, it's possible to format array printing in a manner similar to Python's formatted string operations.

Using numpy.set_printoptions

The numpy.set_printoptions function allows you to customize the precision and suppression of scientific notation for printed NumPy arrays.

To set the precision to, for example, three decimal places, use:

np.set_printoptions(precision=3)
Copy after login

To suppress scientific notation for small numbers, use:

np.set_printoptions(suppress=True)
Copy after login

Using the numpy.printoptions Context Manager

In NumPy version 1.15.0 and later, you can use the numpy.printoptions context manager to apply print options locally:

with np.printoptions(precision=3, suppress=True):
    print(x)
Copy after login

Custom Formatting with the formatter Parameter

To prevent zeros from being truncated from the end of floats, you can use the formatter parameter:

np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
Copy after login

This allows you to specify a format function for each type. In this example, the format function preserves trailing zeros.

The above is the detailed content of How Can I Pretty-Print NumPy Arrays with Controlled Precision and Scientific Notation Suppression?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template