Armin
Armin

Reputation: 361

Different format for saving data in np.savetxt

I have a set of data in a matrix form (different rows and columns). The elements of this matrix can vary from 1.e-7 to 1.e+8. The question is: Is there a way to loop or define (or an alternative way) of saving the elements based on their orders. For instance, if the element is less than 100 fmt = '%.3f' and if the element is more than 100 save in the scientific way in np.savetxt python?

Upvotes: 0

Views: 359

Answers (1)

Bonlenfum
Bonlenfum

Reputation: 20155

The format specifier %g is a quick/clean way to select the form depending on the input (see savetxt docs):

g,G : use the shorter of e,E or f

As an example:

X = 10.0**np.arange(-10,10, 3)
np.savetxt("foo.txt", X, fmt="%5g")

Gives you output with the more extreme values in standard form ("scientific notation"), but those closer to 1 in a plainer format.

$ cat foo.txt
1e-10
1e-07
0.0001
  0.1
  100
100000
1e+08

Upvotes: 2

Related Questions