Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop jupyter notebook wrapping cell contents in pandas html table output

Tags:

The pandas option max_colwidth controls how many characters will be included in the repr of a dataframe:

import string, random
import pandas as pd
df = pd.DataFrame([''.join(random.choice(string.ascii_lowercase + ' ') for j in range(1000)) for i in range(4)])

pd.options.display.max_colwidth = 10
print(df)

yields

           0
0  lmftge...
1  pqttqb...
2  wi wgy...
3  ow dip...

and

pd.options.display.max_colwidth = 30
print(df)

yields

                               0
0  lmftgenioerszvgzfaxorzciow...
1  pqttqbqqe pykgguxnjsspbcti...
2  wi wgybtgcbxkobrwnaxpxwsjc...
3  ow dippaiamvvcofvousieckko...

And you can set pd.options.display.max_colwidth = 0 to remove the limit altogether. Fine so far!

But if the dataframe is rendered in HTML inside a notebook, the notebook will wrap the table of the column to the width of the display, regardless of this setting:

wrapped table

Is there any way to avoid this, i.e. to have the HTML table column rendered as wide as is necessary to fit the each row on a single line?

More generally, is it possible to control the width of HTML table columns in notebook output independent of the number of characters in the pandas output?

like image 971
mike Avatar asked Jun 09 '16 03:06

mike


2 Answers

Building on Ben's answer, but without needing to go into the custom css files, which work differently for juptyter lab.

Just put this in a cell and run it:

%%html
<style>
.dataframe td {
    white-space: nowrap;
}
</style>
like image 109
SnowFrogger Avatar answered Sep 28 '22 09:09

SnowFrogger


If you make a file: ~/.jupyter/custom$ atom custom.css and then put this in it:

.dataframe td {
    white-space: nowrap;
}

Then it will force the cell to show as one line, but then you get a scrolling table.

enter image description here

If you want it to not scroll, then set:

div.output_subarea {
    overflow-x: inherit;
}

and then it'll be as wide as it needs to be:

enter image description here

It's not super pretty, but I'm sure that you can tidy it up if needs be.

I found this very helpful. You'll also need to restart the notebook after you first create the css file for it to register, but from then on you can just refresh the page to see the changes to the css take effect.

This was the notebook that I was testing on.

like image 32
Ben Avatar answered Sep 28 '22 08:09

Ben