scrollex scrollex - 2 months ago 27
Python Question

Can I set variable column widths in pandas?

I've got several columns with long strings of text in a pandas data frame, but am only interested in examining one of them. Is there a way to use something along the lines of

pd.set_option('max_colwidth', 60)
but for a single column only, rather than expanding the width of all the columns in my df?

Answer

If you want to change the display in a Jupyter Notebook, you can use the Style feature. To use this formatting for only some columns simply indicate the column(s) to enlarge thanks to the subset parameter. This is basically HTML and CSS.

### Test data
df = DataFrame({'text': ['foo foo foo foo foo foo foo foo', 'bar bar bar bar bar'],
                 'number': [1, 2]})

df.style.set_properties(subset=['text'], **{'width': '300px'})

enter image description here

Comments