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

```

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

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

```

    [[ 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]]
    
```
CC BY-SA 3.0
2017-07-15T03:20:15.343
36377
2017-07-15T10:28:01.293
2017-07-15T10:28:01.293
3054
23859
question
python python3 numpy
NumPy配列の各要素にカンマを付けて出力する方法
[numpy.array2string](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array2string.html
"numpy.array2string") でカンマ区切りの文字列にできますが，すべての要素についてしまいます．

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

```

    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]]
    
```
CC BY-SA 3.0
2017-07-15T07:40:37.070
36381
2017-07-15T07:40:37.070
24196
36377
answer