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

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

    Unutbu gave a really complete answer (they got a +1 from me too), but here is a lo-tech alternative:

    >>> x=np.random.randn(5)
    >>> x
    array([ 0.25276524,  2.28334499, -1.88221637,  0.69949927,  1.0285625 ])
    >>> ['{:.2f}'.format(i) for i in x]
    ['0.25', '2.28', '-1.88', '0.70', '1.03']
    

    As a function (using the format() syntax for formatting):

    def ndprint(a, format_string ='{0:.2f}'):
        print [format_string.format(v,i) for i,v in enumerate(a)]
    

    Usage:

    >>> ndprint(x)
    ['0.25', '2.28', '-1.88', '0.70', '1.03']
    
    >>> ndprint(x, '{:10.4e}')
    ['2.5277e-01', '2.2833e+00', '-1.8822e+00', '6.9950e-01', '1.0286e+00']
    
    >>> ndprint(x, '{:.8g}')
    ['0.25276524', '2.283345', '-1.8822164', '0.69949927', '1.0285625']
    

    The index of the array is accessible in the format string:

    >>> ndprint(x, 'Element[{1:d}]={0:.2f}')
    ['Element[0]=0.25', 'Element[1]=2.28', 'Element[2]=-1.88', 'Element[3]=0.70', 'Element[4]=1.03']
    

提交回复
热议问题