Fancy Printing a NumPy Array

I’ve been writing computer programs for many years. Early on I noticed that I enjoy coding algorithms but I don’t enjoy coding user interfaces. My idea of an elegant user interface is a shell command.

I was working with Python and its NumPy library for arrays. For some reason I went mentally berserk and decided to write a function that displays a NumPy vector in a pretty format.

The key to such a pretty-print function is understanding a basic print statement like

print("% 8.3f" % x)

This means print x with 3 decimals and a total width of 8 spaces, (and because of the blank space after the % character) using a minus sign if x is negative or a blank space if x is positive. 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()

When finished, I didn’t get the thrill of victory that I get when I code up a cool algorithm, but I was mildly satisfied.

I guess the moral of the story is to find those things that you’re good at because you’ll enjoy working on them more and get better. But you can’t always do the fun stuff, sometimes you have to put on your big boy pants and do tedious or unpleasant work.



These are definitely not Big Boy pants.

This entry was posted in Miscellaneous. Bookmark the permalink.