5

我有一些带有长字段的表格数据。Pandas 会像这样切断一些长字段:

            shortname                                              title  \
0                 shc                     Shakespeare His Contemporaries   
1  folger-shakespeare           Folger Shakespeare Library Digital Texts   
2     perseus-c-greek                            Perseus Canonical Greek   
3      stanford-1880s  Adult British Fiction of the 1880s, Assembled ...   
4       reuters-21578                                      Reuters-21578   
5            ecco-tcp  Eighteenth Century Collections Online / Text C...   

    centuries  
0  16th, 17th  
1  16th, 17th  
2         NaN  
3         NaN  
4         NaN  
5        18th  

如果我使用tabulate.tabulate(),它看起来像这样:

-  ------------------  --------------------------------------------------------------------------  ----------
0  shc                 Shakespeare His Contemporaries                                              16th, 17th
1  folger-shakespeare  Folger Shakespeare Library Digital Texts                                    16th, 17th
2  perseus-c-greek     Perseus Canonical Greek                                                     nan
3  stanford-1880s      Adult British Fiction of the 1880s, Assembled by the Stanford Literary Lab  nan
4  reuters-21578       Reuters-21578                                                               nan
5  ecco-tcp            Eighteenth Century Collections Online / Text Creation Partnership ECCO-TCP  18th
-  ------------------  --------------------------------------------------------------------------  ----------

在第一种情况下,宽度设置为 80 左右,我猜,并且不会扩展以填充终端窗口。我希望列“shortname”、“title”和“centuries”位于同一行,所以这不起作用。

在第二种情况下,宽度设置为数据的宽度,但是如果标题很长,并且如果用户的终端窗口较小,它将非常奇怪地换行。

所以我正在寻找的是 Python 中的一种(最好是简单的)方法,可以根据用户的终端宽度漂亮地打印表格数据,或者至少允许我指定用户的终端宽度,我将在其他地方得到,比如tabulate(data, 120)120列。有没有办法做到这一点?

4

1 回答 1

2

我在 pandas 文档中稍作研究后发现了这一点。这就是我现在正在做的事情:

table = df[fields]
width = pandas.util.terminal.get_terminal_size() # find the width of the user's terminal window
pandas.set_option('display.width', width[0]) # set that as the max width in Pandas
print(table)
于 2016-01-12T20:13:52.037 回答