Setting the fmt option in numpy.savetxt
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
This link might be helpful.
From the link:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content.
When no explicit alignment is given, preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of '0' with an alignment type of '='.
The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer values.