from pprint import pprint
pprint(the_list)
Answer from John La Rooy on Stack Overflowcode golf - Pretty print my arrays - Code Golf Stack Exchange
Pretty print a numpy array
Pretty-print array matlab-style?
python - Pretty print and substitute numpy arrays - Stack Overflow
Python 2, 74 73 72 bytes
-1 thanks to loopy walt
-1 thanks to dingledooper
f=lambda l,s=',\n ':l<[f]and`l`or'[ %s ]'%s.join(f(r,s+' ')for r in l)
Try it online!
JavaScript (SpiderMonkey), 69 bytes
(g=j=>a=>+(u=uneval(a))[1]?u:`[ ${a.map(g(j+' ')).join(j)} ]`)`,
`
Try it online!
This answer assume the array only contains positive integers.
In MATLAB, when I enter a matrix with wildly varying magnitudes of the values, e.g. due to containing numerical noise, I get a nice pretty printed representation such as
>> K
K =
1.0e+09 *
0.0002 0 0 0 0 -0.0010
0 0.0001 0 0 0 0
0 0 0.0002 0.0010 0 0
0 0 0.0010 1.0562 0 0
0 0 0 0 1.0000 0
-0.0010 0 0 0 0 1.0562Is there any way to get a similar representation in numpy without writing my own helper function?
As an example, similar output would be obtained with
K = numpy.genfromtxt("""
200.0000e+003 0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000 -1.0000e+006
0.0000e+000 100.0000e+003 0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000
0.0000e+000 0.0000e+000 200.0000e+003 1.0000e+006 0.0000e+000 0.0000e+000
0.0000e+000 0.0000e+000 1.0000e+006 1.0562e+009 0.0000e+000 0.0000e+000
0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000 1.0000e+009 0.0000e+000
-1.0000e+006 0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000 1.0562e+009
""".splitlines())
factor = 1e9
print(f"{factor:.0e} x")
for row in K:
for cell in row:
print(f"{cell/factor:10.6f}", end=" ")
print()giving
1e+09 x 0.000200 0.000000 0.000000 0.000000 0.000000 -0.001000 0.000000 0.000100 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000200 0.001000 0.000000 0.000000 0.000000 0.000000 0.001000 1.056200 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 -0.001000 0.000000 0.000000 0.000000 0.000000 1.056200
but more effort would be needed to mark zeros as clearly as in MATLAB.
Ok, I'm a molecular biologist and not a professional programmer, so bear with me.
In my very naΓ―f opinion, which you shouldn't take into much consideration, one of the options is to make your own version of pprint, aware of numpy's ndarray objects, and printing them the way you want them.
What I did, and it worked with me, is to open the pprint module (under the Lib directory) and create a modified copy, like this:
(I pasted the working, modified code on pastebin, you can find it here )
First, in the import section, have it try to import numpy's ndarray, by adding:
try:
from numpy import ndarray
np_arrays = True
except ImportError:
np_arrays = False
Then, in the definition of the _format function, right after this:
# This is already there
if self._depth and level > self._depth:
write(rep)
return
(so at line 154 in my copy, after the imports) you should add:
# Format numpy.ndarray object representations
if np_arrays and issubclass(typ, ndarray):
write('array(dtype:' + str(object.dtype))
write('; shape: ' + str(object.shape) + ')')
return
(then the function continues with, r = getattr(typ, "__repr__", None)...)
Now save this script in the same Lib directory where pprint is, with a new name like i.e. mypprint.py and then try:
from mypprint import pprint
pprint.pprint(object_with_np.arrays)
Are you still monitoring this question?
I've been thinking and, if you want to make it more portable, you could just leave the pprint module untouched, and just add a decorator for the _format method in your script, i.e.:
import pprint
import numpy as np
def ndarray_catch(original_format_func):
def _format(*argv):
myobj = argv[1]
if issubclass(type(myobj), np.ndarray):
array_text = 'array(dtype:' + str(myobj.dtype)
array_text +='; shape:' + str(myobj.shape) + ')'
argv = list(argv)
argv[1] = array_text
return original_format_func(*argv)
return _format
pprint.PrettyPrinter._format = ndarray_catch(pprint.PrettyPrinter._format)
Try it with:
my_list = [1, 2, {3:4, 5:"I like to import antigravity"}, \
["this is a very very long text", "smalltext",
np.array([[7,8], [9, 10]])], ("here", "there", ["everywhere"])]
pprint.pprint(my_list)
The output is:
[1,
2,
{3: 4, 5: 'I like to import antigravity'},
['this is a very very long text',
'smalltext',
'array(dtype:int32; shape:(2L, 2L))'],
('here', 'there', ['everywhere'])]
Use numpy.set_printoptions to set the precision of the output:
import numpy as np
x = np.random.random(10)
print(x)
# [ 0.07837821 0.48002108 0.41274116 0.82993414 0.77610352 0.1023732
# 0.51303098 0.4617183 0.33487207 0.71162095]
np.set_printoptions(precision=3)
print(x)
# [ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
And suppress suppresses the use of scientific notation for small numbers:
y = np.array([1.5e-10, 1.5, 1500])
print(y)
# [ 1.500e-10 1.500e+00 1.500e+03]
np.set_printoptions(suppress=True)
print(y)
# [ 0. 1.5 1500. ]
To apply print options locally, using NumPy 1.15.0 or later, you could use the numpy.printoptions context manager.
For example, inside the with-suite precision=3 and suppress=True are set:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
But outside the with-suite the print options are back to default settings:
print(x)
# [ 0.07334334 0.46132615 0.68935231 0.75379645 0.62424021 0.90115836
# 0.04879837 0.58207504 0.55694118 0.34768638]
If you are using an earlier version of NumPy, you can create the context manager yourself. For example,
import numpy as np
import contextlib
@contextlib.contextmanager
def printoptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
x = np.random.random(10)
with printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
To prevent zeros from being stripped from the end of floats:
np.set_printoptions now has a formatter parameter which allows you to specify a format function for each type.
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)
which prints
[ 0.078 0.480 0.413 0.830 0.776 0.102 0.513 0.462 0.335 0.712]
instead of
[ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
Use np.array_str to apply formatting to only a single print statement. It gives a subset of np.set_printoptions's functionality.
For example:
In [27]: x = np.array([[1.1, 0.9, 1e-6]] * 3)
In [28]: print(x)
[[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]
[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]
[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]]
In [29]: print(np.array_str(x, precision=2))
[[ 1.10e+00 9.00e-01 1.00e-06]
[ 1.10e+00 9.00e-01 1.00e-06]
[ 1.10e+00 9.00e-01 1.00e-06]]
In [30]: print(np.array_str(x, precision=2, suppress_small=True))
[[ 1.1 0.9 0. ]
[ 1.1 0.9 0. ]
[ 1.1 0.9 0. ]]