removing scientific notation ONLY for the zero values when printing a numpy array?

Viewed 123

Right now my array prints like this:

  [[ 1.5531e-01 -4.6594e-02  0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00]
 [-4.6594e-02  1.5531e-01  0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00]
 [ 0.0000e+00  0.0000e+00  4.0381e-01  0.0000e+00  0.0000e+00  0.0000e+00]
 [-0.0000e+00 -0.0000e+00 -0.0000e+00  1.9826e+03 -5.9479e+02 -0.0000e+00]
 [ 0.0000e+00  0.0000e+00  0.0000e+00 -5.9479e+02  1.9826e+03  0.0000e+00]
 [ 0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00  5.1549e+03]]

What I would like is:

[[ 1.4531e-01 -4.6594e-02  0           0           0           0         ]
 [-4.6594e-02  1.4531e-01  0           0           0           0         ]
 [ 0           0           4.0381e-01  0           0           0         ]
 [ 0           0           0           1.9826e+03 -5.9479e+02  0         ]
 [ 0           0           0          -5.9479e+02  1.9826e+03  0         ]
 [ 0           0           0           0           0           5.1549e+03]]

Key differences:

  • top row is aligned
  • zero values show up as "0", without the negative sign.

I'm printing out a lot of arrays, so I would prefer to have it be something that you can set instead of having to pass every array through a function in order to format it. Is there something from np.set_printoptions that has this functionality?

1 Answers

Sure, you can specify a formatter in np.set_printoptions, according to docs. The line of code below, sets a right padding to number equal to zero, otherwise prints them in scientific notation, keeping the sign.

np.set_printoptions(formatter={'all': lambda x: '{:<11d}'.format(int(x)) if x == 0 else "{:+.4e}".format(x)})

This is the output you get:

[[+1.5531e-01 -4.6594e-02 0           0           0           0          ]
 [-4.6594e-02 +1.5531e-01 0           0           0           0          ]
 [0           0           +4.0381e-01 0           0           0          ]
 [0           0           0           +1.9826e+03 -5.9479e+02 0          ]
 [0           0           0           -5.9479e+02 +1.9826e+03 0          ]
 [0           0           0           0           0           +5.1549e+03]]
Related