np.set_printoptions allows to customize the pretty printing of numpy arrays. For different use cases, however, I would like to have different printing options.
Ideally, this would be done without having to redefine the whole options each time. I was thinking on using a local scope, something like:
with np.set_printoptions(precision=3):
print my_numpy_array
However, set_printoptions doesn't seem to support with statements, as an error is thrown (AttributeError: __exit__). Is there any way of making this work without creating your own pretty printing class? This is, I know that I can create my own Context Manager as:
class PrettyPrint():
def __init__(self, **options):
self.options = options
def __enter__(self):
self.back = np.get_printoptions()
np.set_printoptions(**self.options)
def __exit__(self, *args):
np.set_printoptions(**self.back)
And use it as:
>>> print A
[ 0.29276529 -0.01866612 0.89768998]
>>> with PrettyPrint(precision=3):
print A
[ 0.293 -0.019 0.898]
Is there, however, something more straightforward (preferably already built-in) than creating a new class?
So based on the link given by @unutbu, instead of using
with np.set_printoptions(precision=3):
print (my_numpy_array)
we should use:
with np.printoptions(precision=3):
print my_numpy_array
which works on my case. If things don't seem changed, try to manipulate other parameters for print options, e.g. linewidth = 125, edgeitems = 7, threshold = 1000 and so forth.
Try
np.array_repr(x, precision=6, suppress_small=True)
Or one of the related functions that take keywords like precision. Looks like it can control many, if not all, of the print options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With