How do I print an aligned numpy array with (text) row and column labels?

后端 未结 4 1082
轮回少年
轮回少年 2020-12-31 08:22

Is there any elegant way to exploit the correct spacing feature of print numpy.array to get a 2D array, with proper labels, that aligns properly? For example, g

4条回答
  •  -上瘾入骨i
    2020-12-31 08:53

    Here's a way to leverage the array printing functions. I probably wouldn't use it, but it comes pretty close to meeting your requirements!

    a = np.random.rand(5,4)
    x = np.array('col1 col2 col3 col4'.split())
    y = np.array('row1 row2 row3 row4 row5'.split())
    b = numpy.zeros((6,5),object)
    b[1:,1:]=a
    b[0,1:]=x
    b[1:,0]=y
    b[0,0]=''
    printer = np.vectorize(lambda x:'{0:5}'.format(x,))
    print printer(b).astype(object)
    
    [[     col1 col2 col3 col4]
     [row1 0.95 0.71 0.03 0.56]
     [row2 0.56 0.46 0.35 0.90]
     [row3 0.24 0.08 0.29 0.40]
     [row4 0.90 0.44 0.69 0.48]
     [row5 0.27 0.10 0.62 0.04]]
    

提交回复
热议问题