7

It seems quit trivial to me but I'm still missing an efficient and "clean" way to insert a series of element belonging to numpy array (as aa[:,:]) in a formatted string to be printed/written. In fact the extended element-by-element specification syntaxes like:

formattedline= '%10.6f  %10.6f  %10.6f' % (aa[ii,0], aa[ii,1], aa[ii,2]) 
file1.write(formattedline+'\n')

are working.

But I have not found any other shorter solution, because:

formattedline= '%10.6f  %10.6f  %10.6f' % (float(aa[ii,:]))
file1.write(formattedline+'\n')

of course gives: TypeError: only length-1 arrays can be converted to Python scalars

or:

formattedline= '%10.6f  %10.6f  %10.6f' % (aa[ii,:]) 
file1.write(formattedline+'\n')

gives: TypeError: float argument required, not numpy.ndarray. I have tried with iterators but with no success.

Of course this is interesting when there are several elements to be printed.

So: how can I combine iteration over numpy array and string formatted fashion?

Pierre GM
  • 19,809
  • 3
  • 56
  • 67
gluuke
  • 1,179
  • 6
  • 15
  • 22

2 Answers2

6

You could convert it to a tuple:

formattedline = '%10.6f  %10.6f  %10.6f' % ( tuple(aa[ii,:]) )

In a more general case you could use a join:

formattedline = ' '.join('%10.6f'%F for F in aa[ii,:] )
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • that is good and working! :) ... so the second solution is actually iterating over the numpy array, very nice. – gluuke Oct 05 '12 at 11:49
  • ... but still, adding one string: `formattedline= ' %4s %10.6f %10.6f %10.6f' % (string1, (tuple(aa[ii,:])))` gives `TypeError: float argument required, not tuple` and I don't understand why – gluuke Oct 05 '12 at 12:00
  • @gluuke you need to add them: `(string1,)+tuple(aa[ii,:])`. – Andy Hayden Oct 05 '12 at 12:23
2

If you are writing the entire array to a file, use np.savetxt:

np.savetxt(file1, aa, fmt = '%10.6f')

The fmt parameter can be a single format, or a sequence of formats, or a multi-format string like

'%10.6f  %5.6f  %d'
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • ... thanks! But what about if I'm not saving the whole array at the same time? ... So if I'm adding slices of array combined with some text? – gluuke Oct 05 '12 at 11:46
  • Then I think @hayden's suggestion is best. Under the hood, `np.savetxt` calls `fh.write(asbytes(format % tuple(row) + newline))`. (In Python2, `asbytes = str`.) – unutbu Oct 05 '12 at 11:49