The function below may be used to set both the number of decimal places and the fixed width of NumPy print out. If no width is given it defaults to zero (no extra padding added). Setting width will ensure alignment of output.

import numpy as np
# We can set NumPy to print to a fixed number of decimal places:
# e.g. the 8 decimal places that are standard, with no set width
np.set_printoptions(formatter={'float': lambda x: "{0:0.8f}".format(x)})
# Or to make things more flexible/clearer in the code we can set up a function.
# This function will define both fixed with and decimal placed/
# If no width is given it will default to zero, with no extra spacing added
def set_numpy_decimal_places(places, width=0):
set_np = '{0:' + str(width) + '.' + str(places) + 'f}'
np.set_printoptions(formatter={'float': lambda x: set_np.format(x)})

Interests are use of simulation and machine learning in healthcare, currently working for the NHS and the University of Exeter. Committed to all work being performed in Free and Open Source Software (FOSS), and as much source data being made available as possible.
https://gitlab.com/michaelallen1966
View all posts by Michael Allen

Published

One thought on “64. NumPy: Setting width and number of decimal places in NumPy print output”

## One thought on “64. NumPy: Setting width and number of decimal places in NumPy print output”