1

I have output that looks like this

AB%CD3_SW3Z_1000 uvsec_czrkup_rmplr SeightRveZargrp def_move 35.8% 28.0% 16.2% 120 0.0010
MN%P03_AT%W00_500 uvsec_czrkup_rmplr SeightRveZargrp def_move 28.8% 24.7% 23.4% 94 0.1000
KE_A03_UVA%Q00_100 uvsec_czrkup_rmplr SeightRveZargrp def_move 27.2% 11.8% 3.5% 398 0.010

What is the cleanest, most elegant way to format it as

AB%CD3_SW3Z_1000   uvsec_czrkup_rmplr SeightRveZargrp def_move 35.8% 28.0% 16.2% 120 0.0010
MN%P03_AT%W00_500  uvsec_czrkup_rmplr SeightRveZargrp def_move 28.8% 24.7% 23.4% 94 0.1000
KE_A03_UVA%Q00_100 uvsec_czrkup_rmplr SeightRveZargrp def_move 27.2% 11.8% 3.5% 398 0.010

Of course, I am asking in general case, assuming each line has the same number of tokens. I want columns to be left-alligned.

Baron Yugovich
  • 3,843
  • 12
  • 48
  • 76

2 Answers2

1

One way you could do this is to use str.ljust(width) (assuming you've converted everything into a string) to pad each token in each line to make every token in a column the same width. To determine what width you want to use, either set a fixed width (if you know the maximum possible length of a token) or perhaps set the fixed width for each column by getting the largest entry in each column.

c. leather
  • 86
  • 1
  • 6
1

I have used PrettyTables for this type of application in the past and this function:

def format_df(df):    
    table = PrettyTable([''] + list(df.columns))
    for row in df.itertuples():
        table.add_row(row)
    return str(table)

A full example, using your input looks like this:

import pandas as pd
from prettytable import PrettyTable

def format_df(df):    
    table = PrettyTable([''] + list(df.columns))
    for row in df.itertuples():
        table.add_row(row)
    return str(table)

df = pd.read_clipboard(header=None)   # No header provided on example input
print(format_df(df))

This generates the following output. The headers are named poorly because there were not headers provided in your sample data:

+---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+
|   |         0          |         1          |        2        |    3     |   4   |   5   |   6   |  7  |   8   |
+---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+
| 0 |  AB%CD3_SW3Z_1000  | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 35.8% | 28.0% | 16.2% | 120 | 0.001 |
| 1 | MN%P03_AT%W00_500  | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 28.8% | 24.7% | 23.4% |  94 |  0.1  |
| 2 | KE_A03_UVA%Q00_100 | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 27.2% | 11.8% |  3.5% | 398 |  0.01 |
+---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+
Andy
  • 49,085
  • 60
  • 166
  • 233