Home > Backend Development > Python Tutorial > How Can I Pretty-Print NumPy Arrays Without Scientific Notation and Maintain Precision?

How Can I Pretty-Print NumPy Arrays Without Scientific Notation and Maintain Precision?

Patricia Arquette
Release: 2024-12-07 02:21:11
Original
822 people have browsed it

How Can I Pretty-Print NumPy Arrays Without Scientific Notation and Maintain Precision?

Pretty-print NumPy Arrays: Avoiding Scientific Notation and Ensuring Precision

NumPy arrays typically display with decimals in scientific notation, making them difficult to interpret. To format arrays for readability, consider the following solutions:

Using numpy.set_printoptions

The numpy.set_printoptions function allows you to modify the printing options for arrays. By setting precision to the desired number of decimal places, you can format the floats as desired. Additionally, setting suppress to True removes scientific notation for small numbers.

import numpy as np

x = np.random.random(10)
np.set_printoptions(precision=3, suppress=True)
print(x)  # Prints [0.073  0.461  0.689 ...]
Copy after login

Using a Context Manager

The NumPy 1.15.0 and later provides a context manager for numpy.printoptions. Within this context, any print operations will use the specified print options.

with np.printoptions(precision=3, suppress=True):
    print(x)  # Within the context, options are set
print(x)  # Outside the context, options are back to default.
Copy after login

Preventing Trailing Zeros Removal

To preserve trailing zeros, use the formatter parameter of np.set_printoptions. This allows you to define a custom format function for each data type.

np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)  # Prints [0.078  0.480  0.413 ...]
Copy after login

The above is the detailed content of How Can I Pretty-Print NumPy Arrays Without Scientific Notation and Maintain Precision?. 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