Following this idea for pretty printing of numpy ndarrays, I have developed a very primitive prototype:
def ndtotext(A, w=None, h=None):
if A.ndim==1:
if w == None :
return str(A)
else:
s ='['+' '*(max(w[-1],len(str(A[0])))-len(str(A[0]))) +str(A[0])
for i,AA in enumerate(A[1:]):
s += ' '*(max(w[i],len(str(AA)))-len(str(AA))+1)+str(AA)
s +='] '
elif A.ndim==2:
w1 = [max([len(str(s)) for s in A[:,i]]) for i in range(A.shape[1])]
w0 = sum(w1)+len(w1)+1
s= u'\u250c'+u'\u2500'*w0+u'\u2510' +'\n'
for AA in A:
s += ' ' + ndtotext(AA, w=w1) +'\n'
s += u'\u2514'+u'\u2500'*w0+u'\u2518'
elif A.ndim==3:
h=A.shape[1]
s1=u'\u250c' +'\n' + (u'\u2502'+'\n')*h + u'\u2514'+'\n'
s2=u'\u2510' +'\n' + (u'\u2502'+'\n')*h + u'\u2518'+'\n'
strings=[ndtotext(a)+'\n' for a in A]
strings.append(s2)
strings.insert(0,s1)
s='\n'.join(''.join(pair) for pair in zip(*map(str.splitlines, strings)))
return s
for example:
shape = 4, 5, 3
C=np.random.randint(10000, size=np.prod(shape)).reshape(shape)
print(ndtotext(C))
┌┌────────────────┐┌────────────────┐┌────────────────┐┌────────────────┐┐
│ [9298 4404 1759] [5426 3488 9267] [8884 7721 579] [6872 4226 1858] │
│ [6723 271 8466] [9885 6760 8949] [ 295 7422 5659] [5322 4239 7446] │
│ [7156 6077 9390] [2712 6379 2832] [6956 626 5534] [ 142 4090 6390] │
│ [9377 9033 1953] [8986 3791 4538] [2466 8572 662] [1528 8922 9656] │
│ [1449 7319 3939] [7350 9619 928] [7542 4704 1477] [ 980 6037 869] │
└└────────────────┘└────────────────┘└────────────────┘└────────────────┘┘
I would appreciate it if you could review this code and let me know how I can improve it.
I hope to see:
- possible mistakes or cases to break the code
- how to make it faster, more performant, pythonic
- how to extend it to higher dimensions
P.S. For those who follow up this idea I have integrated everythin here in this Jupyter Notebook
w
look like? \$\endgroup\$w
. \$\endgroup\$