string representation of a numpy array with commas separating its elements

后端 未结 4 974
無奈伤痛
無奈伤痛 2020-12-15 15:06

I have a numpy array, for example:

points = np.array([[-468.927,  -11.299,   76.271, -536.723],
                   [-429.379, -694.915, -214.689,  745.763],         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-15 15:53

    The function you are looking for is np.set_string_function. source

    What this function does is let you override the default __str__ or __repr__ functions for the numpy objects. If you set the repr flag to True, the __repr__ function will be overriden with your custom function. Likewise, if you set repr=False, the __str__ function will be overriden. Since print calls the __str__ function of the object, we need to set repr=False.

    For example:

    np.set_string_function(lambda x: repr(x), repr=False)
    x = np.arange(5)
    print(x)
    

    will print the output

    array([0, 1, 2, 3, 4])
    

    A more aesthetically pleasing version is

    np.set_string_function(lambda x: repr(x).replace('(', '').replace(')', '').replace('array', '').replace("       ", ' ') , repr=False)
    
    print(np.eye(3))
    

    which gives

    [[1., 0., 0.],
     [0., 1., 0.],
     [0., 0., 1.]]
    

    Hope this answers your question.

提交回复
热议问题