Knowing that np.savetxt
only works for 1D or 2D arrays, the general idea is:
- when
fmt
is a single formatting string it applies to all elements in the
array (1D or 2D input array)
- when
fmt
is a sequence of formatting strings, it applies to each column of the 2D input array
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