formatted string of series of numpy array elements

gluuke picture gluuke · Oct 5, 2012 · Viewed 9.8k times · Source

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?

Answer

Andy Hayden picture Andy Hayden · Oct 5, 2012

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,:] )