I have recently noticed that Python printing functionality is not consistent for NumPy ndarays. For example it prints a horizontal 1D array horizontally:
import numpy as np
A1=np.array([1,2,3])
print(A1)
#--> [1 2 3]
but a 1D horizontal array with redundant brackets vertically:
A2=np.array([[1],[2],[3]])
print(A2)
#--> [[1]
# [2]
# [3]]
a 1D vertical array horizontally:
A3=np.array([[1,2,3]])
print(A3)
#--> [[1 2 3]]
and a 2D array:
B=np.array([[11,12,13],[21,22,23],[31,32,32]])
print(B)
# --> [[11 12 13]
# [21 22 23]
# [31 32 32]]
where the first dimension is now vertical. It gets even worse for higher dimensions as all of them are printed vertically:
C=np.array([[[111,112],[121,122]],[[211,212],[221,222]]])
print(C)
#--> [[[111 112]
# [121 122]]
#
# [[211 212]
# [221 222]]]
A consistent behavior in my opinion would be to print the even dimensions horizontally and odd ones vertically. Using Unicode characters it would be possible to format it nicely. I was wondering if it is possible to create a function to print above arrays as:
A1 --> [1 2 3]
A2 --> ┌┌─┐┌─┐┌─┐┐
│ 1 2 3 │
└└─┘└─┘└─┘┘
A3 --> ┌┌─┐┐ # u250cu2500u2510
│ 1 │ # u2502
│ 2 │
│ 3 │
└└─┘┘ # u2514u2500u2518
B --> ┌┌──┐┌──┐┌──┐┐
│ 11 21 31 │
│ 12 22 32 │
│ 13 23 33 │
└└──┘└──┘└──┘┘
C --> ┌┌─────────┐┌─────────┐┐
│ [111 112] [211 212] │
│ [121 122] [221 222] │
└└─────────┘└─────────┘┘
I found this gist which takes care of the different number of digits. I tried to prototype a recursive function to implement the above concept:
def npprint(A):
assert isinstance(A, np.ndarray), "input of npprint must be array like"
if A.ndim==1 :
print(A)
else:
for i in range(A.shape[1]):
npprint(A[:,i])
It kinda works for A1
, A2
, A3
and B
but not for C
. I would appreciate if you could help me know how the npprint
should be to achieve above output for arbitrary dimension numpy ndarrays?
P.S.1. In Jupyter environment one can use LaTeX mathtools
underbracket
and overbracket
in Markdown. Sympy's pretty printing functionality is also a great start point. It can use ASCII, Unicode, LaTeX...
P.S.2. I'm being told that there is indeed a consistency in the way ndarrays are being printed. however IMHO it is kind of wired and non-intuitive. Having a flexible pretty printing function could help a lot to display ndarrays in different forms.
P.S.3. Sympy guys have already considered both points I have mentioned here. their Matrix module is pretty consistent (A1
and A2
are the same) and they also have a pprint
function which does kind of the same thing and I expect from npprint here.
P.S.4. For those who follow up this idea I have integrated everythin here in this Jupyter Notebook
See Question&Answers more detail:
os