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

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

    FYI Numpy 1.15 (release date pending) will include a context manager for setting print options locally. This means that the following will work the same as the corresponding example in the accepted answer (by unutbu and Neil G) without having to write your own context manager. E.g., using their example:

    x = np.random.random(10)
    with np.printoptions(precision=3, suppress=True):
        print(x)
        # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]
    
    0 讨论(0)
  • 2020-11-22 04:38

    The gem that makes it all too easy to obtain the result as a string (in today's numpy versions) is hidden in denis answer: np.array2string

    >>> import numpy as np
    >>> x=np.random.random(10)
    >>> np.array2string(x, formatter={'float_kind':'{0:.3f}'.format})
    '[0.599 0.847 0.513 0.155 0.844 0.753 0.920 0.797 0.427 0.420]'
    
    0 讨论(0)
  • 2020-11-22 04:40

    You can use set_printoptions to set the precision of the output:

    import numpy as np
    x=np.random.random(10)
    print(x)
    # [ 0.07837821  0.48002108  0.41274116  0.82993414  0.77610352  0.1023732
    #   0.51303098  0.4617183   0.33487207  0.71162095]
    
    np.set_printoptions(precision=3)
    print(x)
    # [ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]
    

    And suppress suppresses the use of scientific notation for small numbers:

    y=np.array([1.5e-10,1.5,1500])
    print(y)
    # [  1.500e-10   1.500e+00   1.500e+03]
    np.set_printoptions(suppress=True)
    print(y)
    # [    0.      1.5  1500. ]
    

    See the docs for set_printoptions for other options.


    To apply print options locally, using NumPy 1.15.0 or later, you could use the numpy.printoptions context manager. For example, inside the with-suite precision=3 and suppress=True are set:

    x = np.random.random(10)
    with np.printoptions(precision=3, suppress=True):
        print(x)
        # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]
    

    But outside the with-suite the print options are back to default settings:

    print(x)    
    # [ 0.07334334  0.46132615  0.68935231  0.75379645  0.62424021  0.90115836
    #   0.04879837  0.58207504  0.55694118  0.34768638]
    

    If you are using an earlier version of NumPy, you can create the context manager yourself. For example,

    import numpy as np
    import contextlib
    
    @contextlib.contextmanager
    def printoptions(*args, **kwargs):
        original = np.get_printoptions()
        np.set_printoptions(*args, **kwargs)
        try:
            yield
        finally: 
            np.set_printoptions(**original)
    
    x = np.random.random(10)
    with printoptions(precision=3, suppress=True):
        print(x)
        # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]
    

    To prevent zeros from being stripped from the end of floats:

    np.set_printoptions now has a formatter parameter which allows you to specify a format function for each type.

    np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
    print(x)
    

    which prints

    [ 0.078  0.480  0.413  0.830  0.776  0.102  0.513  0.462  0.335  0.712]
    

    instead of

    [ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]
    
    0 讨论(0)
  • 2020-11-22 04:48

    And here is what I use, and it's pretty uncomplicated:

    print(np.vectorize("%.2f".__mod__)(sparse))
    
    0 讨论(0)
  • 2020-11-22 04:48

    I often want different columns to have different formats. Here is how I print a simple 2D array using some variety in the formatting by converting (slices of) my NumPy array to a tuple:

    import numpy as np
    dat = np.random.random((10,11))*100  # Array of random values between 0 and 100
    print(dat)                           # Lines get truncated and are hard to read
    for i in range(10):
        print((4*"%6.2f"+7*"%9.4f") % tuple(dat[i,:]))
    
    0 讨论(0)
  • 2020-11-22 04:48

    I use

    def np_print(array,fmt="10.5f"):
        print (array.size*("{:"+fmt+"}")).format(*array)
    

    It's not difficult to modify it for multi-dimensional arrays.

    0 讨论(0)
提交回复
热议问题