Question

In numpy there is a function that makes arrays print prettier.

set_printoptions(suppress = True)

In other words, instead of this:

array([[  0.00000000e+00,  -3.55271368e-16,   0.00000000e+00,
          1.74443793e-16,   9.68149172e-17],
       [  5.08273978e-17,  -4.42527959e-16,   1.57859836e-17,
          1.35982590e-16,   5.59918137e-17],
       [  3.00000000e+00,   6.00000000e+00,   9.00000000e+00,
          2.73835608e-16,   7.37061982e-17],
       [  2.00000000e+00,   4.00000000e+00,   6.00000000e+00,
          4.50218574e-16,   2.87467529e-16],
       [  1.00000000e+00,   2.00000000e+00,   3.00000000e+00,
          2.75582605e-16,   1.88929494e-16]])

You get this:

array([[ 0., -0.,  0.,  0.,  0.],
       [ 0., -0.,  0.,  0.,  0.],
       [ 3.,  6.,  9.,  0.,  0.],
       [ 2.,  4.,  6.,  0.,  0.],
       [ 1.,  2.,  3.,  0.,  0.]])

How do I make this setting permanent so it does this whenever I'm using IPython?

Was it helpful?

Solution

I added this to the main() function in ~/.ipython/ipy_user_conf.py:

from numpy import set_printoptions
set_printoptions(suppress = True)

and it seems to work.

In later IPython versions, run ipython profile create, then open ~\.ipython\profile_default\ipython_config.py and edit the following line to add the command:

c.InteractiveShellApp.exec_lines = [
        ...
        'import numpy as np',
        'np.set_printoptions(suppress=True)',
        ...
        ]

OTHER TIPS

You can add those to your ipythonrc file (located in ~/.ipython on Unix). You'd need the lines:

import_mod numpy
execute numpy.set_printoptions(suppress = True)

You can also add it to a custom profile or use another configuration method:

http://ipython.scipy.org/doc/stable/html/config/customization.html

Well, one way to streamline it would be to create a wee module somewhere on your $PYTHONPATH, printopts say, containing:

import numpy
numpy.set_printoptions(suppress = True)

And then import that whenever you want to change the printing. You could also import numpy in your code as from printopts import numpy. That way you'd only need one import statement.

Cheers.

ADDENDUM: A solution for interactive use only is to set the $PYTHONSTARTUP environment variable to the path to the printopts.py file. The interpreter executes that file before anything else, when in interactive mode. Of course, then python will always load numpy, hurting start times.

Having considered a little more, what I would do is create a module, say np.py containing

from numpy import *
set_printoptions(supress=True)

Then always import np to get your modified version, for the reason in my comment below.

If you don't mind a hack, just add the set_printoptions() call to the numpy/__init__.py file, but you have to have write access to the numpy installation and remember to repeat the hack when you update python or numpy. I don't think this is a good idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top