NumPy配列の各要素にカンマを付けて出力する方法


例えば、(6,6)の次の配列の出力を

[code]

    [[ 0.0000  0.3505 -0.6385  0.6240 -0.3382  0.0111]
     [ 0.3505  1.2691  0.0000  0.0000  0.0000  0.3503]
     [-0.6385  0.0000  0.7116  0.0000  0.0000  0.6385]
     [ 0.6240  0.0000  0.0000 -0.7621  0.0000  0.6240]
     [-0.3382  0.0000  0.0000  0.0000 -1.2549  0.3380]
     [ 0.0111  0.3503  0.6385  0.6240  0.3380  0.0000]]
    
[/code]

次のように各要素にカンマを付けて出力する方法を教えてください。

[code]

    [[ 0.0000,  0.3505, -0.6385,  0.6240, -0.3382,  0.0111]
     [ 0.3505,  1.2691,  0.0000,  0.0000,  0.0000,  0.3503]
     [-0.6385,  0.0000,  0.7116,  0.0000,  0.0000,  0.6385]
     [ 0.6240,  0.0000,  0.0000, -0.7621,  0.0000,  0.6240]
     [-0.3382,  0.0000,  0.0000,  0.0000, -1.2549,  0.3380]
     [ 0.0111,  0.3503,  0.6385,  0.6240,  0.3380,  0.0000]]
    
[/code]




[numpy.array2string](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array2string.html
"numpy.array2string") でカンマ区切りの文字列にできますが，すべての要素についてしまいます．

厳密に出力例のようにするのであれば，効率的ではないですが例えば下のような関数でできます．

[code]

    import numpy as np
    
    ary = np.array([
        [ 0.0000,  0.3505, -0.6385,  0.6240, -0.3382,  0.0111],
        [ 0.3505,  1.2691,  0.0000,  0.0000,  0.0000,  0.3503],
        [-0.6385,  0.0000,  0.7116,  0.0000,  0.0000,  0.6385],
        [ 0.6240,  0.0000,  0.0000, -0.7621,  0.0000,  0.6240],
        [-0.3382,  0.0000,  0.0000,  0.0000, -1.2549,  0.3380],
        [ 0.0111,  0.3503,  0.6385,  0.6240,  0.3380,  0.0000]])
    
    print(np.array2string(ary, separator=', ', formatter={'float_kind': lambda x: '{: .4f}'.format(x)}))
    
    # [[ 0.0000,  0.3505, -0.6385,  0.6240, -0.3382,  0.0111],
    #  [ 0.3505,  1.2691,  0.0000,  0.0000,  0.0000,  0.3503],
    #  [-0.6385,  0.0000,  0.7116,  0.0000,  0.0000,  0.6385],
    #  [ 0.6240,  0.0000,  0.0000, -0.7621,  0.0000,  0.6240],
    #  [-0.3382,  0.0000,  0.0000,  0.0000, -1.2549,  0.3380],
    #  [ 0.0111,  0.3503,  0.6385,  0.6240,  0.3380,  0.0000]]
    
    def format_array(ary):
        n = len(ary) - 1
        ret = "["
        for i, x in enumerate(ary):
            if i != 0:
                ret += ' '
            ret += '['
            ret += ', '.join(['{: .4f}'.format(xx) for xx in x])
            ret += ']'
            if i != n:
                ret += '\n'
        ret += ']'
        return ret
    
    print(format_array(ary))
    
    # [[ 0.0000,  0.3505, -0.6385,  0.6240, -0.3382,  0.0111]
    #  [ 0.3505,  1.2691,  0.0000,  0.0000,  0.0000,  0.3503]
    #  [-0.6385,  0.0000,  0.7116,  0.0000,  0.0000,  0.6385]
    #  [ 0.6240,  0.0000,  0.0000, -0.7621,  0.0000,  0.6240]
    #  [-0.3382,  0.0000,  0.0000,  0.0000, -1.2549,  0.3380]
    #  [ 0.0111,  0.3503,  0.6385,  0.6240,  0.3380,  0.0000]]
    
[/code]

