pythonarraysstringnumpysave

Setting the fmt option in numpy.savetxt


I am looking at the numpy.savetxt, and am stuck at the fmt option.

I tried looking at here and also the reference in the link below all the letters that can be used for the fmt option sort give me a general sense of what is going on.

What I do not understand is if the % symbol is required and in an example given here how should I interpret the 10.5 number? If "f" is about setting the floating point, then how come is it 10.5 (then again, I might not know how floating points are set...).


Solution

  • Knowing that np.savetxt only works for 1D or 2D arrays, the general idea is:

    I'm presenting here some examples using the following input array:

    import numpy as np
    
    a = np.array([[11, 12, 13, 14],
                  [21, 22, 23, 24],
                  [31, 32, 33, 34]])
    

    1) Setting floating point precision: np.savetxt('tmp.txt', a, fmt='%1.3f')

    11.000 12.000 13.000 14.000
    21.000 22.000 23.000 24.000
    31.000 32.000 33.000 34.000
    

    2) Adding characters to right-justify.

    With spaces: np.savetxt('tmp.txt', a, fmt='% 4d')

      11   12   13   14
      21   22   23   24
      31   32   33   34
    

    With zeros: np.savetxt('tmp.txt', a, fmt='%04d')

    0011 0012 0013 0014
    0021 0022 0023 0024
    0031 0032 0033 0034
    

    3) Adding characters to left-justify (use of "-").

    With spaces: np.savetxt('tmp.txt', a, fmt='%-4d')

    11   12   13   14  
    21   22   23   24  
    31   32   33   34  
    

    4) When fmt is a sequence of formatting strings, each row of a 2D input array is processed according to fmt:

    fmt as a sequence in a single formatting string

    fmt = '%1.1f + %1.1f / (%1.1f * %1.1f)'
    np.savetxt('tmp.txt', a, fmt=fmt)
    
    11.0 + 12.0 / (13.0 * 14.0)
    21.0 + 22.0 / (23.0 * 24.0)
    31.0 + 32.0 / (33.0 * 34.0)
    

    fmt as an iterator of formatting strings:

    fmt = '%d', '%1.1f', '%1.9f', '%1.9f'
    np.savetxt('tmp.txt', a, fmt=fmt)
    
    11 12.0 13.000000000 14.000000000
    21 22.0 23.000000000 24.000000000
    31 32.0 33.000000000 34.000000000