Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local scope for numpy set_printoptions

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?

like image 466
Imanol Luengo Avatar asked Feb 07 '23 16:02

Imanol Luengo


2 Answers

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.

like image 94
Jason Avatar answered Feb 11 '23 00:02

Jason


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.

like image 31
hpaulj Avatar answered Feb 10 '23 23:02

hpaulj