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

后端 未结 14 2186
臣服心动
臣服心动 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:52

    You can get a subset of the np.set_printoptions functionality from the np.array_str command, which applies only to a single print statement.

    http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html

    For example:

    In [27]: x = np.array([[1.1, 0.9, 1e-6]]*3)
    
    In [28]: print x
    [[  1.10000000e+00   9.00000000e-01   1.00000000e-06]
     [  1.10000000e+00   9.00000000e-01   1.00000000e-06]
     [  1.10000000e+00   9.00000000e-01   1.00000000e-06]]
    
    In [29]: print np.array_str(x, precision=2)
    [[  1.10e+00   9.00e-01   1.00e-06]
     [  1.10e+00   9.00e-01   1.00e-06]
     [  1.10e+00   9.00e-01   1.00e-06]]
    
    In [30]: print np.array_str(x, precision=2, suppress_small=True)
    [[ 1.1  0.9  0. ]
     [ 1.1  0.9  0. ]
     [ 1.1  0.9  0. ]]
    
    0 讨论(0)
  • 2020-11-22 04:55

    Yet another option is to use the decimal module:

    import numpy as np
    from decimal import *
    
    arr = np.array([  56.83,  385.3 ,    6.65,  126.63,   85.76,  192.72,  112.81, 10.55])
    arr2 = [str(Decimal(i).quantize(Decimal('.01'))) for i in arr]
    
    # ['56.83', '385.30', '6.65', '126.63', '85.76', '192.72', '112.81', '10.55']
    
    0 讨论(0)
提交回复
热议问题