How to pretty-print a numpy.array without scientific notation and with given precision?

后端 未结 14 2354
臣服心动
臣服心动 2020-11-22 04:28

I\'m curious, whether there is any way to print formatted numpy.arrays, e.g., in a way similar to this:

x = 1.23456
print \'%.3f\' % x
         


        
14条回答
  •  滥情空心
    2020-11-22 04:29

    I find that the usual float format {:9.5f} works properly -- suppressing small-value e-notations -- when displaying a list or an array using a loop. But that format sometimes fails to suppress its e-notation when a formatter has several items in a single print statement. For example:

    import numpy as np
    np.set_printoptions(suppress=True)
    a3 = 4E-3
    a4 = 4E-4
    a5 = 4E-5
    a6 = 4E-6
    a7 = 4E-7
    a8 = 4E-8
    #--first, display separate numbers-----------
    print('Case 3:  a3, a4, a5:             {:9.5f}{:9.5f}{:9.5f}'.format(a3,a4,a5))
    print('Case 4:  a3, a4, a5, a6:         {:9.5f}{:9.5f}{:9.5f}{:9.5}'.format(a3,a4,a5,a6))
    print('Case 5:  a3, a4, a5, a6, a7:     {:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7))
    print('Case 6:  a3, a4, a5, a6, a7, a8: {:9.5f}{:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7,a8))
    #---second, display a list using a loop----------
    myList = [a3,a4,a5,a6,a7,a8]
    print('List 6:  a3, a4, a5, a6, a7, a8: ', end='')
    for x in myList: 
        print('{:9.5f}'.format(x), end='')
    print()
    #---third, display a numpy array using a loop------------
    myArray = np.array(myList)
    print('Array 6: a3, a4, a5, a6, a7, a8: ', end='')
    for x in myArray:
        print('{:9.5f}'.format(x), end='')
    print()
    

    My results show the bug in cases 4, 5, and 6:

    Case 3:  a3, a4, a5:               0.00400  0.00040  0.00004
    Case 4:  a3, a4, a5, a6:           0.00400  0.00040  0.00004    4e-06
    Case 5:  a3, a4, a5, a6, a7:       0.00400  0.00040  0.00004    4e-06  0.00000
    Case 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000    4e-07  0.00000
    List 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000
    Array 6: a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000
    

    I have no explanation for this, and therefore I always use a loop for floating output of multiple values.

提交回复
热议问题