How to output each element of a NumPy array with a comma

Asked 1 years ago, Updated 1 years ago, 76 views

For example, the output of the next array of (6, 6) is

 [[0.0000.3505-0.63850.6240-0.33820.011]
 [ 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]]

How do I output each element with a comma as follows?

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

python python3 numpy

2022-09-30 21:26

1 Answers

numpy.array2string can be a comma-separated string, but it will cover all elements.

If you're going to do it exactly like an example output, you can do it with a function that's not efficient, but for example, below.

import numpy as np

aary=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':lambdax:'{:.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]]


2022-09-30 21:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.