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

后端 未结 4 1066
轮回少年
轮回少年 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条回答
  •  别那么骄傲
    2020-12-31 08:49

    Assuming all matrix numbers have at most 3 digits, you could replace the last part with this:

    print "     A   B   C   D   E"
    for row_label, row in zip(row_labels, x):
        print '%s [%s]' % (row_label, ' '.join('%03s' % i for i in row))
    

    Which outputs:

         A   B   C   D   E
    Z [ 85  86  87  88  89]
    Y [ 90 191 192  93  94]
    X [ 95  96  97  98  99]
    W [100 101 102 103 104]
    

    Formatting with '%03s' results in a string of length 3 with left padding (using spaces). Use '%04s' for length 4 and so on. The full format string syntax is explained in the Python documentation.

提交回复
热议问题