Tabulate according to terminal width in python?
Asked Answered
M

1

6

I have some tabular data with some long fields. Pandas will cut off some of the long fields like this:

            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  

and if I use tabulate.tabulate(), it looks like this:

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

In the first case, the width is set to around 80, I'm guessing, and doesn't expand to fill the terminal window. I would like the columns "shortname," "title," and "centuries" to be on the same line, so this doesn't work.

In the second case, the width is set to the width of the data, but that won't work if there's a very long title, and if the user has a smaller terminal window, it will wrap really strangely.

So what I'm looking for is a (preferably easy) way in Python to pretty-print tabular data according to the user's terminal width, or at least allow me to specify the user's terminal width, which I will get elsewhere, like tabulate(data, 120) for 120 columns. Is there a way to do that?

Maraca answered 12/1, 2016 at 19:53 Comment(0)
M
2

I figured it out with a little poking around the pandas docs. This is what I'm doing now:

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)
Maraca answered 12/1, 2016 at 20:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.