Home >Backend Development >Python Tutorial >How Can I Pretty-Print NumPy Arrays Without Scientific Notation and Maintain 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 ...]
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.
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 ...]
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!