Jon*_*han 6 python tui command-line-interface 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
Run Code Online (Sandbox Code Playgroud)
如果我使用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
- ------------------ -------------------------------------------------------------------------- ----------
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,我猜测宽度设置为 80 左右,并且不会扩展以填充终端窗口。我希望“短名称”、“标题”和“世纪”列位于同一行,所以这是行不通的。
在第二种情况下,宽度设置为数据的宽度,但是如果标题很长,则该方法不起作用,并且如果用户的终端窗口较小,它会非常奇怪地换行。
所以我正在寻找一种(最好是简单的)Python 方法,根据用户的终端宽度漂亮地打印表格数据,或者至少允许我指定用户的终端宽度,我将在其他地方获得它,例如tabulate(data, 120)120列。有没有办法做到这一点?
我通过查阅 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)
Run Code Online (Sandbox Code Playgroud)