[Numpy-discussion] printing array in tabular form

Daniele Nicolodi daniele at grinta.net
Fri May 10 08:51:55 EDT 2013


On 10/05/2013 13:20, Sudheer Joseph wrote:

> Hi,
> I am trying to learn Python after feeling its utility in coding and
> also reading a bit aboutits potential only, please do not put words
> in to my mouth like below.

I didn't put words in your mouth, I simply quoted emails you sent to the
list and gave my interpretation of what you wrote.

>>> Before denigrating a programming language
> 
> 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

For references about string formatting in Python:

http://docs.python.org/2/library/string.html#formatstrings
http://docs.python.org/2/library/stdtypes.html#string-formatting

for the numpy array to text formatting:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

writing a function to do what you ask is trivial. Unfortunately there is
no "format the thing as I wish" function.

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")


Cheers,
Daniele




More information about the NumPy-Discussion mailing list