Search code examples
pythonpandasprettytable

Python prettytable get_string error


I have a pandas data frame like

>>> df
Out[126]: 
      score        id
0  0.999989    654153
1  0.992971    941351
2  0.979518    701608
3  0.972667    564000
4  0.936928    999843

and want to convert to a prettytable (in order to write to a text file with a better readability)

import prettytable as pt
x = pt.PrettyTable()
for col in list(df.columns):
    x.add_column(col,df[col])

then inside a function, I use

print(x.get_string())

and get this error

File "<ipython-input-130-8db747160a67>", line 5, in <module>
verbose   = True)

File "<ipython-input-129-4e27c067e0b5>", line 104, in lda_save_eval
print(x.get_string())

File "C:\Users\USER\Anaconda3\envs\tensorflow\lib\site-packages\prettytable.py", line 990, in get_string
self._compute_widths(formatted_rows, options)

File "C:\Users\USER\Anaconda3\envs\tensorflow\lib\site-packages\prettytable.py", line 894, in _compute_widths
widths = [_get_size(field)[0] for field in self._field_names]

File "C:\Users\USER\Anaconda3\envs\tensorflow\lib\site-packages\prettytable.py", line 894, in <listcomp>
widths = [_get_size(field)[0] for field in self._field_names]

File "C:\Users\USER\Anaconda3\envs\tensorflow\lib\site-packages\prettytable.py", line 77, in _get_size
lines = text.split("\n")

AttributeError: 'int' object has no attribute 'split'

Any clues?


Solution

  • try print (x.get_string()) instead of print(x.get_string)

    For improvement try this, In order to write to a text file with a better readability you don't need for loop use tabulate it gives you more flexible.

    try this,

    from tabulate import tabulate
    print (tabulate(df,df.columns,tablefmt='psql'))
    

    In tablefmt you can provide many options to get different styles. for more details refer this link