0

I am trying to print to file with np.savetxt arrays of multiple formats as show below:

import numpy as np
f = open('./multiple_format.dat', 'w')
c1 = np.array(['A', 'B'])
n1 =  np.array([1.545446367853, 6.8218467347894])
n2 =  np.array([1.546715887182, 2.9718145367852])

np.savetxt(f, np.column_stack([c1, np.around(n1, decimals = 3), np.round(n2, 3)]), fmt='%s', delimiter='\t')

I have already seen two answers at A1 and A2, some of the answers in those posts require the character width to be specified and accordingly white space is provided before the string array if it is shorter than this width as shown below:

import numpy as np
f = open('./multiple_format.dat', 'w')
c1 = np.array(['A', 'B'])
n1 =  np.array([1.545446367853, 6.8218467347894])
n2 =  np.array([1.546715887182, 2.9718145367852])

A['v1'] = c1
A['v2'] = n1

np.savetxt(f, A, fmt="%10s %10.3f")

I don't need leading space before the string and I need np.savetxt to print arrays of multiple data formats with control on precision of floats. How can this be done in Python?

Community
  • 1
  • 1
Tom Kurushingal
  • 6,086
  • 20
  • 54
  • 86

1 Answers1

0

The core of savetxt is

         for row in X:
            try:
                fh.write(asbytes(format % tuple(row) + newline))

It iterates on the rows of your array, and applies

 format % tuple(row)

to turn it into a string.

format is constructed from your fmt parameter. In your case with 2 % items it uses thefmt` as is:

In [95]: "%10s %10.3f"%tuple(np.array([1.545446367853, 6.8218467347894]))
Out[95]: '1.54544636785      6.822'

So when it comes to spacing and precision, you are at the mercy of the standard Python formatting system. I'd suggest playing with that kind of expression directly.

In [96]: "%.2f, %10.3f"%tuple(np.array([1.545446367853, 6.8218467347894]))
Out[96]: '1.55,      6.822'
In [97]: "%.2f, %.10f"%tuple(np.array([1.545446367853, 6.8218467347894]))
Out[97]: '1.55, 6.8218467348'
In [106]: (', '.join(["%.2e"]*2))%tuple([1.545446367853, 6.8218467347894])
Out[106]: '1.55e+00, 6.82e+00'
hpaulj
  • 221,503
  • 14
  • 230
  • 353