如何打印与(文本)行和列标签对齐numpy的阵列?

问题描述:

有没有利用打印numpy.array 的正确间距功能来获取二维数组,适当的标签,即正确对准任何优雅的方式?例如,给出4行5列的数组,我怎么能提供相应的行和标题列阵列和适当大小列表生成一些输出,看起来像这样?

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, given an array with 4 rows and 5 columns, how can I provide the array and appropriately sized lists corresponding to the row and header columns to generate some output that looks like this?

      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]]

如果我天真的尝试:

import numpy
x = numpy.array([[85, 86, 87, 88, 89], \
                 [90, 191, 192, 93, 94], \
                 [95, 96, 97, 98, 99], \
                 [100,101,102,103,104]])

row_labels = ['Z', 'Y', 'X', 'W']


print "     A   B   C   D   E"
for row, row_index in enumerate(x):
    print row_labels[row_index], row

我得到:

      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]

有什么办法,我可以得到的东西智能排队?我肯定是开放给使用任何其他图书馆是否有更好的方法来解决我的问题。

Is there any way i can get things to line up intelligently? I am definitely open to using any other library if there is a better way to solve my problem.

假设所有的矩阵人数最多3个数字,你可以用这个代替的最后一部分:

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))

它输出:

     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]

格式化'%03S 长3左填充(用空格)的字符串结果。使用'%04S 的长度为4等。完整的格式字符串语法是Python文档中解释。

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.