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?

2 Answers 2

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,:] )
Sign up to request clarification or add additional context in comments.

3 Comments

that is good and working! :) ... so the second solution is actually iterating over the numpy array, very nice.
... 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 you need to add them: (string1,)+tuple(aa[ii,:]).
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'

2 Comments

... 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?
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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.