Python打印对齐的numpy数组

问题描述 投票:0回答:2

当我通过以下方式打印numpy数组时:

print('Array: ', A)

结果格式错误:

Array: [[0.0000 0.5000]
 [0.0000 0.3996]]

相反,我想'正确'对齐:

Array: [[0.0000 0.5000]
        [0.0000 0.3996]]
python-3.x numpy
2个回答
1
投票

改进显示的最简单方法是分离标签和数组打印:

In [13]: print('Array:');print(np.arange(4).reshape(2,2))
Array:
[[0 1]
 [2 3]]

In [14]: print('Array', np.arange(4).reshape(2,2))
Array [[0 1]
 [2 3]]

print将字符串与数组的str格式组合在一起:

In [15]: print('Array', str(np.arange(4).reshape(2,2)))
Array [[0 1]
 [2 3]]
In [16]: str(np.arange(4).reshape(2,2))
Out[16]: '[[0 1]\n [2 3]]'

str(A)独立于更大的背景,所以只有小缩进,而不是你想要的大缩进。

为了更接近您想要的结果,您必须自己拆分并组合这些字符串。


变种产生同样的东西:

In [19]: print('Array\n{}'.format(np.arange(4).reshape(2,2)))
Array
[[0 1]
 [2 3]]

In [22]: print('Array',np.arange(4).reshape(2,2),sep='\n')
Array
[[0 1]
 [2 3]]

这就是我在拆分和重建时的想法:

In [26]: alist = str(np.arange(6).reshape(3,2)).splitlines()
In [27]: alist
Out[27]: ['[[0 1]', ' [2 3]', ' [4 5]]']
In [28]: header = 'Array: '; offset = '       '
In [29]: astr = [header + alist[0]]
In [30]: for row in alist[1:]:
    ...:     astr.append(offset + row)
    ...:     
In [31]: astr
Out[31]: ['Array: [[0 1]', '        [2 3]', '        [4 5]]']
In [32]: print('\n'.join(astr))
Array: [[0 1]
        [2 3]
        [4 5]]

0
投票

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

但是请参考Andy P的回复,请注意你也可以打印所有没有标签就好了

这段代码本质上是上面scoffey的一个实现,但它没有三个字符的限制,而且功能更强大一些。这是我的代码:

    def format__1(digits,num):
        if digits<len(str(num)):
            raise Exception("digits<len(str(num))")
        return ' '*(digits-len(str(num))) + str(num)
    def printmat(arr,row_labels=[], col_labels=[]): #print a 2d numpy array (maybe) or nested list
        max_chars = max([len(str(item)) for item in flattenList(arr)+col_labels]) #the maximum number of chars required to display any item in list
        if row_labels==[] and col_labels==[]:
            for row in arr:
                print '[%s]' %(' '.join(format__1(max_chars,i) for i in row))
        elif row_labels!=[] and col_labels!=[]:
            rw = max([len(str(item)) for item in row_labels]) #max char width of row__labels
            print '%s %s' % (' '*(rw+1), ' '.join(format__1(max_chars,i) for i in col_labels))
            for row_label, row in zip(row_labels, arr):
                print '%s [%s]' % (format__1(rw,row_label), ' '.join(format__1(max_chars,i) for i in row))
        else:
            raise Exception("This case is not implemented...either both row_labels and col_labels must be given or neither.")

赛跑

    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']
    column_labels = ['A', 'B', 'C', 'D', 'E']
    printmat(x,row_labels=row_labels, col_labels=column_labels)

         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]

如果'x'只是嵌套的python列表而不是numpy数组,那么这也是输出。

© www.soinside.com 2019 - 2024. All rights reserved.