[Numpy-discussion] printing array in tabular form

Derek Homeier derek at astro.physik.uni-goettingen.de
Fri May 10 08:40:15 EDT 2013


On 10.05.2013, at 1:20PM, Sudheer Joseph <sudheer.joseph at yahoo.com> wrote:

> If some one has a quick way I would like to learn from them or get a referecence 
> where the formatting part is described which was 
> my intention while posting here. As I have been using fortran I just tried 
> to use it to explain my requirement
> 
Admittedly the formatting options in Python can be confusing to beginners, precisely
since they are much more powerful than for many other languages. As already pointed
out, formats of the type '(5i5)' are very common to Fortran programs and thus readily
supported by the language. np.savetxt is just a convenience function to support a number
of similarly common output types, and it can create csv, tab-separated, or plenty of other
outputs from a numpy array just out of the box. 
But you added to the confusion as you did not make it clear that you were not just requiring
a plain csv file as your Fortran example would create (and the first version did not even
have the commas); since this is a rather non-standard form you will just have to write a
short loop yourself, wether you are using Fortran or Python.

>                          Infact the program which should read this file requires it in specified format which should look like
> IL = 1,2,3,4,5
>      1,2,3,4,5
>      1,2,3,4,5
> 
The formats are all documented http://docs.python.org/2/library/string.html#format-specification-mini-language
one important thing to know is that you can pretty much add (i.e. concatenate) them like strings:

print(("%6s"+4*"%d,"+"%d\n") % (("IL = ",)+tuple(IL[:5])))

or, perhaps a bit clearer:

fmt = "%6s"+4*"%d,"+"%d\n"
print_t = ("IL = ",)+tuple(IL[:5])
print(fmt % print_t)

The other important bit to keep in mind is that all arguments have to be passed as tuples.
This should allow you to write a loop to print with a "header" or an empty header column
for the subsequent lines as you see fit. 
Except for the string field which is explicitly formatted "%s" here, this is mostly equivalent
to the example Henry just posted.

HTH,
					Derek




More information about the NumPy-Discussion mailing list