🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί pprint.html
pprint β€” Data pretty printer
The pprint module provides a capability to β€œpretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the ...
Discussions

code golf - Pretty print my arrays - Code Golf Stack Exchange
But it's a pain to do by hand and it'd be nice to have a program that does this for me. Your challenge is to create a program that does this for me, taking a multidimensional array containing only positive integers and prettyprinting it. Specifically, an array of depth 1 is printed joined by ... More on codegolf.stackexchange.com
🌐 codegolf.stackexchange.com
February 18, 2022
Pretty print a numpy array
I would like to make a suggestion. Often when I work with matrices I want to see them. Take the following example: A = np.random.normal(size=(8,8)) If I print this matrix, the result looks like thi... More on github.com
🌐 github.com
14
October 5, 2019
Pretty-print array matlab-style?
You can do this: np.set_printoptions(formatter={'all': lambda x: "{:.4g}".format(x)}) It doesn't do everything you want, but the 4g in the format should show 0.0 as 0, .0003 as .0003, and 1e9 ast 1e+9. columns will not be lined up. More on reddit.com
🌐 r/Numpy
3
3
September 22, 2023
python - Pretty print and substitute numpy arrays - Stack Overflow
Imagine am pretty printing a JSON-decoded object that has the structure: {Stack Layer Material } Where these variables correspond to a hierarchy of structures in a More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί how do i pretty print a 2d array in python?
How do I pretty print a 2D array in Python? : r/learnpython
November 20, 2017 - If you pass multiple arguments to the print function it's what separates each item (it just so happens " " is also the default, but I included for brevity). In this example, the print(*a) syntax passes all the items of a as individual arguments.
🌐
Note.nkmk.me
note.nkmk.me β€Ί home β€Ί python
Pretty-print in Python: pprint | note.nkmk.me
May 17, 2023 - If compact is set to True, elements that can fit within width are printed on a single line. This setting is particularly useful for lists with many elements. pprint.pprint(l_long, width=40, compact=True) # [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], # [100, 101, 102, 103, 104, 105, 106, # 107, 108, 109]] ... Note that compact was added in Python 3.4, so it cannot be used in earlier versions.
🌐
Real Python
realpython.com β€Ί python-pretty-print
Prettify Your Data Structures With Pretty Print in Python – Real Python
March 18, 2026 - This is just another part of the pretty in Python’s pprint()! By default, pprint() will only output up to eighty characters per line. You can customize this value by passing in a width argument. pprint() will make an effort to fit the contents on one line. If the contents of a data structure go over this limit, then it’ll print every element of the current data structure on a new line:
🌐
Browse Tutorials
browse-tutorials.com β€Ί snippet β€Ί python-pretty-print-array
Python: Pretty Print Array | Browse Tutorials
May 11, 2016 - Pretty print array, meaning that you print array, dictionary, object or any non string format in human-friendly way. This is great for terminal / command line.
🌐
Python Module of the Week
pymotw.com β€Ί 2 β€Ί pprint
pprint – Pretty-print data structures - Python Module of the Week
$ python pprint_recursion.py id(local_data) => 4299545560 ['a', 'b', 1, 2, <Recursion on list with id=4299545560>] For very deep data structures, you may not want the output to include all of the details. It might be impossible to format the data properly, the formatted text might be too large to manage, or you may need all of it. In that case, the depth argument can control how far down into the nested data structure the pretty printer goes.
Find elsewhere
🌐
GitHub
github.com β€Ί numpy β€Ί numpy β€Ί issues β€Ί 14647
Pretty print a numpy array Β· Issue #14647 Β· numpy/numpy
October 5, 2019 - with np.printoptions(precision=4, suppress=True, formatter={'float': '{:0.4f}'.format}, linewidth=100): print(A)
Author: numpy
Starred by 40 users
Forked by 2 users
Languages: Python
🌐
Reddit
reddit.com β€Ί r/numpy β€Ί pretty-print array matlab-style?
r/Numpy on Reddit: Pretty-print array matlab-style?
September 22, 2023 -

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.0562

Is 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.

Top answer
1 of 2
1

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)  
2 of 2
0

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'])]
🌐
GitHub
gist.github.com β€Ί braingineer β€Ί d801735dac07ff3ac4d746e1f218ab75
Pretty print a matrix in Python 3 with numpy Β· GitHub
Very useful for small arrays. ... This topic might interest you. Over there I have tried to picture a pretty printing function for numpy and other people have suggested interesting prototypes as well.
Top answer
1 of 1
9

If A.ndim is not in 1, 2, 3, your code tries to return a non-existing string s. It would be better to be explicit about what your code supports atm:

def ndtotext(A, w=None, h=None):
    ...
    else:
        raise NotImplementedError("Currently only 1 - 3 dimensions are supported")
    return s

While we are at the point of having your code be clear about what is happening, you should add a docstring explaining what your code does:

def ndtotext(A, w=None, h=None):
    """Returns a string to pretty print the numpy.ndarray `A`.

    Currently supports 1 - 3 dimensions only.
    Raises a NotImplementedError if an array with more dimensions is passed.

    Describe `w` and `h`.
    """
    ...

Next, Python has an official style-guide, PEP8, which programmers are encouraged to follow. One of the things it recommends is surrounding operators with spaces (which I fixed in the rest of the code) and using lower_case for variables and functions (which I left as is for now).

Now, let's come to your actual code:

  • You calculate some values multiple times (like str(A[0])), save those to a variable.
  • If you want to compare to None, use is (since it is a singleton).
  • No else needed after an if...return (this is a matter of personal style, I prefer not having the additional level of indentation).
  • Use str.rjust to add enough whitespace in front of your strings. You could also use str.format for this, but it looks less nice.
  • Your w has a weird structure, with the width of the first column being the last entry and the rest starting at zero.
  • Give the unicode values names. And then add functions to draw a line of specified length.
  • String addition is costly and slow. Try to consistently use building a list and str.joining it.

    UPPER_LEFT = u'\u250c'
    UPPER_RIGHT = u'\u2510'
    LOWER_LEFT = u'\u2514'
    LOWER_RIGHT = u'\u2518'
    HORIZONTAL = u'\u2500'
    VERTICAL = u'\u2502'
    
    def upper_line(width):
        return UPPER_LEFT + HORIZONTAL * width + UPPER_RIGHT
    
    def lower_line(width):
        return LOWER_LEFT + HORIZONTAL * width + LOWER_RIGHT
    
    def left_line(height):
        return "\n".join([UPPER_LEFT] + [VERTICAL] * height + [LOWER_LEFT])
    
    def right_line(height):
        return "\n".join([UPPER_RIGHT] + [VERTICAL] * height + [LOWER_RIGHT])
    
    def ndtotext(A, w=None, h=None):
        """Returns a string to pretty print the numpy.ndarray `A`.
    
        Currently supports 1 - 3 dimensions only.
        Raises a NotImplementedError if an array with more dimensions is passed.
    
        Describe `w` and `h`.
        """
        if A.ndim == 1:
            if w is None:
                return str(A)
            s = " ".join([str(value).rjust(width) for value, width in zip(A, w)])
            return '[{}]'.format(s)
        elif A.ndim == 2:
            widths = [max([len(str(s)) for s in A[:, i]]) for i in range(A.shape[1])]
            s = "".join([' ' + ndtotext(AA, w=widths) + ' \n' for AA in A])
            w0 = sum(widths) + len(widths) - 1 + 2 # spaces between elements and corners
            return upper_line(w0) + '\n'  + s + lower_line(w0)
        elif A.ndim == 3:
            h = A.shape[1]
            strings = [left_line(h)]
            strings.extend(ndtotext(a) + '\n' for a in A)
            strings.append(right_line(h))
            return '\n'.join(''.join(pair) for pair in zip(*map(str.splitlines, strings)))
        raise NotImplementedError("Currently only 1 - 3 dimensions are supported")
    

This can probably be even more compactified, but I think it is a good start.

Example usage:

x = np.arange(12)

print(ndtotext(x))
[ 0  1  2  3  4  5  6  7  8  9 10 11]

print(ndtotext(x.reshape(3, 4)))
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 [0 1  2  3] 
 [4 5  6  7] 
 [8 9 10 11] 
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

print(ndtotext(x.reshape(3, 2, 2)))
β”Œβ”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”β”
β”‚ [0 1]  [4 5]  [ 8  9] β”‚
β”‚ [2 3]  [6 7]  [10 11] β”‚
β””β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”˜β”˜
🌐
Delft Stack
delftstack.com β€Ί "delft stack" β€Ί "howto" β€Ί "python how-to's" β€Ί "how to pretty print a dictionary in python"
How to Pretty Print a Dictionary in Python | Delft Stack
February 2, 2024 - Within the pprint module there is a function with the same name pprint(), which is the function used to pretty-print the given string or object. First, declare an array of dictionaries.
Top answer
1 of 14
800

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]
2 of 14
89

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. ]]
🌐
James D. McCaffrey
jamesmccaffreyblog.com β€Ί home β€Ί fancy printing a numpy array
Fancy Printing a NumPy Array - James D. McCaffreyJames D. McCaffrey
May 15, 2019 - With that in hand I added a vals_line parameter for use with big arrays to control how many values per line to display. Finally, I decided to print the values in yellow to make them stand out. And, drum roll please β€” Β· # test.py import numpy as np import os os.system('color') def show_vec(v, wid, dec, vals_line): print("\033[0m" + "\033[93m", end="") # reset-yellow fmt = "% " + str(wid) + "." + str(dec) + "f" # like % 8.4f for i in range(len(v)): if i != 0 and i % vals_line == 0: print("") print(fmt % v[i] + " ", end="") print("") print("\033[0m", end="") # reset def main(): print("\nBegin\n") unknown_norm = np.array([-1, 0.34, 0, 1, 0.2298], dtype=np.float32) show_vec(unknown_norm, wid=8, dec=4, vals_line=3) print("\nEnd") if __name__ == "__main__": main()
🌐
PyPI
pypi.org β€Ί project β€Ί numpyprint
numpyprint Β· PyPI
NumpyPrint nicely prints an numpy array with the help of the package PrettyTable. It prints arrays of any dimension.
🌐
YouTube
youtube.com β€Ί watch
Pretty-print a NumPy array without scientific notation and with ...
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
🌐
Finxter
blog.finxter.com β€Ί home β€Ί learn python blog β€Ί 5 best ways to print an array in python
5 Best Ways to Print an Array in Python - Be on the Right Side of Change
February 26, 2024 - This approach is great for further manipulating the elements, but it might be a bit overkill just for printing. The pprint() function, part of Python’s pretty-print library, provides a cleaner display of the array by managing the formatting.