-1

Can we get output like below from python?

text1   -9.98442   -10.        -0.01558
text2   -0.         -0.         0.     
text3    0.         -0.        -0.     
text4    0.24829     0.24829   -0.     
text5   -7.40799    -7.40575    0.00224
text6    0.         -0.        -0.     
text7   -0.          0.         0.     
text8   -5.88917    -5.83199    0.05718
text9   -0.          0.         0.     
text10  -6.83455    -6.74592    0.08862

That is text to the left, and period-aligned columns with suppressed small numbers (e.g. from a 1D array of strings and a 2D array of floats).

Numpy can produce the structure of the floats with np.set_printoptions(precision=5,suppress=True) and print(array) but then I don't know how to get the text to the left and preferably get rid of the brackets.

Jonatan Öström
  • 2,428
  • 1
  • 16
  • 27
  • 1
    Look at the following [answer](https://stackoverflow.com/a/24301608/1810479). The `tabulate` package could fit your needs. – TommasoF Apr 18 '18 at 12:08
  • Maybe you should also look at [pandas](https://pandas.pydata.org/). This library provides a DataFrame model, which is a great way to work with table-like data. – Olzhas Arystanov Apr 18 '18 at 12:13
  • @jpp those answers do not suppress small numbers, which is the main point here, otherwise I could just use `string.format()` – Jonatan Öström Apr 18 '18 at 13:47
  • @JonatanÖström, Fair enough. Please can you **[edit](https://stackoverflow.com/posts/49899310/edit)** your question with a more appropriate title? – jpp Apr 18 '18 at 13:50
  • @Georgy I know you are right but reading through peoples failed attempts is really boring, I kind of supply an attempt mentioning the `numpy` output. – Jonatan Öström Apr 18 '18 at 13:50

1 Answers1

0

After spending more time than expected I have a programmatical solution where I chose to totally suppress the zeros.

script.py:

import numpy as np

def printskip(text,mat,tol=5,off=6):
    rows = np.size(mat,0)
    cols = np.size(mat,1)
    lim  = 10**(-tol)
    zero = ' '*off+'-'+' '*tol
    form = ':>'+str(off+tol+1)+'.'+str(tol)+'f}'
    for row in range(rows):
        textform=''
        for i in range(cols):
            if abs(mat[row,i]) < lim:
                txtf = zero 
            else:
                txtf = '{'+str(i)+form
            textform += txtf
        print('{:<10}'.format(text[row]),textform.format(*mat[row,:]))


text = ['dkl', 'dofj', 'ldfj','gasf']
dat = np.array([
[0.2621206 ,   0.1006 ,    0.620606],
[200.0000005 ,   200.3832 , 0.062532e-7],
[10.4001095 ,   0.2393 ,    0.009593],
[0.0373096 ,   1.e-7 ,     1000.809681]
])


printskip(text,dat,5)

python3 script.py

dkl             0.26212     0.10060     0.62061
dofj          200.00000   200.38320      -     
ldfj           10.40011     0.23930     0.00959
gasf            0.03731      -       1000.80968
Jonatan Öström
  • 2,428
  • 1
  • 16
  • 27