[Numpy-discussion] printing array in tabular form

Derek Homeier derek at astro.physik.uni-goettingen.de
Fri May 10 09:36:38 EDT 2013

On 10.05.2013, at 2:51PM, Daniele Nicolodi <daniele at grinta.net> wrote:

> If you wish to format numpy arrays preceding them with a variable name,
> the following is a possible solution that gives the same formatting as
> in your example:
> import numpy as np
> import sys
> def format(out, v, name):
>    header = "{} = ".format(name)
>    out.write(header)
>    np.savetxt(out, v, fmt="%d", delimiter=", ",
>               newline="\n" + " " * len(header))
>    out.write("\n")
> IL = np.array([range(5), ] * 5)
> format(sys.stdout, IL, "IL")

That is a quite ingenuous way to use savetxt functionality to write that extra column!

Only two comments:

Don't call that function "format", as it would mask the 'format' builtin!

In the present version it will only work with a file handle; to print it a to file you would need
to pass it as fformat(open(fname, 'a'), … or check for that case inside the function.


More information about the NumPy-Discussion mailing list