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

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

If I naively try:

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

I get:

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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值