【问题标题】:Python prettytable get_string errorPython漂亮的get_string错误
【发布时间】:2018-12-03 17:00:42
【问题描述】:

我有一个类似的熊猫数据框

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

并希望转换为漂亮的表格(以便写入具有更好可读性的文本文件)

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

然后在函数内部,我使用

print(x.get_string())

得到这个错误

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'

有什么线索吗?

【问题讨论】:

  • 你试过get_string()吗?
  • 对不起,我刚才打错字了...我已经完全尝试过 x.get_string()

标签: python pandas prettytable


【解决方案1】:

尝试print (x.get_string()) 而不是print(x.get_string)

为了改进,试试这个, 为了写入具有更好可读性的文本文件,您不需要循环使用tabulate,它使您更加灵活。

试试这个,

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

tablefmt 中,您可以提供许多选项来获得不同的样式。 更多详情请参考link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-06
    • 2016-04-02
    • 2020-02-13
    • 2021-04-06
    • 1970-01-01
    • 2019-08-24
    • 2018-08-16
    • 2021-11-01
    相关资源
    最近更新 更多