-1

My question is similar to NumPy: Pretty print tabular data however, I do not wish to import any special libraries for this task.

I have a numpy array of the form:

[['Labels' '1' '5']
 ['0 O 1s    ' '0.002664922566805935' '0.11149161266806229']
 ['0 O 2s    ' '0.15992666631848482' '-0.3993420097430756']
 ['0 O 3s    ' '-0.02083386304772113' '0.19091064108525108']
 ['0 O 2px   ' '-4.787613039997692e-09' '3.3802683686891544e-09']
 ['0 O 2py   ' '0.3505418637107196' '0.61656253143151']]

However, I need to print the numbers to 5 decimal places for the core data only and not in the header. An additional problem is the table can involve any number of columns so I need a solution that can handle an unknown number of columns.

The output I am aiming for is:

Labels      1           5
0 O 1s      0.00266     0.11149
0 O 2s      0.15993    -0.39934
0 O 3s     -0.02083     0.19091
0 O 2px     0.00000     0.00000
0 O 2py     0.35054     0.61656
Wychh
  • 656
  • 6
  • 20
  • This question needs a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org/). Please see [How To Ask Questions The Smart Way](http://www.catb.org/~esr/faqs/smart-questions.html). Always provide a complete [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example "Minimal Reproducible Example"). – itprorh66 Jan 28 '22 at 00:19

1 Answers1

1

For the first column, you can use ljust to pad the right side of the string with extra spaces.

For columns 2 and up, you can use rjust plus a format specifier to get a pretty string with padding on the left side so that decimal points always line up nicely.

def print_array_pretty(inarray):
    colwidth = 10
    for i, row in enumerate(inarray):
        outrow = ''
        for j, item in enumerate(row):
            if j == 0:
                outrow += inarray[i,j].ljust(colwidth)
            else:
                if i == 0:
                    outrow += ' '*(colwidth-7) + inarray[i,j].ljust(7)
                else:
                    outrow += format(float(inarray[i,j]), '.5f').rjust(colwidth)
        print(outrow)

print_array_pretty(A)

which gives

Labels       1         5
0 O 1s       0.00266   0.11149
0 O 2s       0.15993  -0.39934
0 O 3s      -0.02083   0.19091
0 O 2px     -0.00000   0.00000
0 O 2py      0.35054   0.61656
bfris
  • 5,272
  • 1
  • 20
  • 37