Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatted string of series of numpy array elements

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?

like image 359
gluuke Avatar asked Oct 05 '12 10:10

gluuke


2 Answers

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,:] )
like image 50
Andy Hayden Avatar answered Nov 10 '22 00:11

Andy Hayden


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'
like image 39
unutbu Avatar answered Nov 10 '22 00:11

unutbu