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?
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,:] )
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With