Vitto Vitto - 3 months ago 57
Python Question

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

Thanks!

Answer

You can use the fmt parameter in many ways, here are some examples to give you some insight.

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

1) np.savetxt('tmp.txt',a, fmt='%1.3f')

11.000 12.000 13.000 14.000
21.000 22.000 23.000 24.000

2) np.savetxt('tmp.txt',a, fmt='%04d')

0011 0012 0013 0014
0021 0022 0023 0024

You can also use to write expressions, like (note that the number of entries in the expression is the same as the number of columns in the array:

3) np.savetxt('tmp.txt',a, fmt='%1.1f + %1.1f / (%1.1f * %1.1f)')

11.0 + 12.0 / (13.0 * 14.0)
21.0 + 22.0 / (23.0 * 24.0)