Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...