Stop jupyter notebook wrapping cell contents in pandas html table output

mike picture mike · Jun 9, 2016 · Viewed 9.1k times · Source

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?

Answer

SnowFrogger picture SnowFrogger · Sep 6, 2019

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>