What are the possible numpy value format strings?

Question:

In numpy, many functions have a string which can be passed as an additional argrument to format numpy array values.

In numpy.loadtxt for example, http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

The following can be chosen

"%10.5f"
"%.4e %+.4j"

And it mentions in the documentation:

“Further explanation of the fmt parameter (%[flag]width[.precision]specifier):”

Exactly what are the possible formats?

What are possible values for flag, width, precision, and specifier ?

Bonus points for someone who explains when they can be mixed and matched… 'Iteration %d – %10.5f’ is mentioned in the documentation…

Asked By: D Adams

||

Answers:

np.savetxt is using the old-fashioned (Py2) % style formatting. The key line is:

for row in X:
    fh.write(asbytes(format % tuple(row) + newline))

where format is your fmt parameter, or constructed from it:

# `fmt` can be a string with multiple insertion points or a
# list of formats.  E.g. '%10.5ft%10d' or ('%10.5f', '$10d')

(I’m puzzled about that ‘$10d’ string. Is that a typo?

In essence if there are enough % in a string fmt, it is used as is. If it’s a list it joins them with the delimited. If a single format, it replicates it and joins.

The row the array is turned into a tuple, which is normal input to % formatting.

So savetxt is straight forward Python number formatting.

I think it’s the only numpy function that operates this way. There’s a separate formatter than handles the print display of arrays.

========================

example:

Fully specified fmt string:

In [22]: np.savetxt('text.txt',np.ones((2,4)),fmt='%s: %10d, %10.5fl %.4e')

In [23]: cat text.txt
1.0:          1,    1.00000l 1.0000e+00
1.0:          1,    1.00000l 1.0000e+00

Use of that fmt directly with a tuple of integers:

In [24]: '%s: %10d, %10.5fl %.4e'%(1,1,1,1)
Out[24]: '1:          1,    1.00000l 1.0000e+00'

and with a tuple of floats (note change the 1st %s format)

In [25]: '%s: %10d, %10.5fl %.4e'%(1.,1.,1.,1.)

Out[25]: '1.0:          1,    1.00000l 1.0000e+00'
Answered By: hpaulj

The possible formats are listed at format specification mini-language in the Python Standard Library documentation.

Width and precision are decimal integers. Unless a minimum field width is defined, the field width will always be the same size as the data to fill it.

Presentation types include:
"b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Answered By: jvl_bioinformatics
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.