Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the possible numpy value format strings?

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...

like image 209
D Adams Avatar asked Oct 16 '25 18:10

D Adams


1 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.5f\t%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'
like image 74
hpaulj Avatar answered Oct 18 '25 13:10

hpaulj