Python Print NumPy 3d Array/Matrix in Readable "Tower" Form

BustACode 0 Tallied Votes 3K Views Share

I have been learning NumPy arrays/matrices in Python.

As I worked, I found that I desired a more readable form of 3d matrices. So I figured that writing one would be a good goal and learning exercise. The goal was to create a function that would print 3d NumPy matrices out in a more readable 'tower' form, but without altering the original matrix or duplicating it . I accomplished the goal, and learned much about NumPy, and output formatting.

If you too desire to have 3d matrices displayed in a more readable form, then this should do the trick.

Enjoy.

Note: Yes, I am not PEP-8 compliant. The code rows are longer than 80 chars. with the comments. Please adjust/modify as needed.

# Python 2.7.10
    # Imports #
from __future__ import print_function
from numpy import *

    # Main #
def main():
    a_Array = arange(27).reshape(3, 3, 3)
    f_Print3dArray(a_Array)

def f_Print3dArray(a_Array):
    """&&Syntax: 3D NUMPY.NDARRAY, returns PRINT;
    Desc.: Takes a NumPy 3d ARRAY and PRINTs in 'tower' form for easy reading.
    Test: a_Array = arange(27).reshape(3, 3, 3)
    f_Print3dArray(a_Array)

      / 2  5  8  /
     / 1  4  7  /
    / 0  3  6  /

      / 11 14 17 /
     / 10 13 16 /
    / 9  12 15 /

      / 20 23 26 /
     / 19 22 25 /
    / 18 21 24 /

    """
    for i in a_Array[:,:,::-1].transpose(0,2,1): ## Get value of each col. of each last col. of each internal matrix as rows, starting with top row.
        for index, j in enumerate(i): ## Get the index and value of each element in modified matrix.
            print(" " * (len(i) - 1 - index) + "/ ", end="") ## Print the leading format chars.
            for k in j: ## Get value of each element in row.
                print(str(k).ljust( (len(str(amax(a_Array)))) + 1), end="") ## Print each element of each row with ljust to max len. of matrices max element.
            print("/") ## Print trailing format chars.
        print() ## Add a row between internal matrixes.

if __name__ == '__main__':
    main()