44

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?

scrollex
  • 2,207
  • 7
  • 23
  • 37

2 Answers2

49

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

Romain
  • 16,760
  • 6
  • 49
  • 57
  • 33
    Unfortunately for me, I don't see this taking any effect with pandas 0.23.0. applying this style to my df and the target column in it, the target column's size remains the same rather than being the value provided for `width`. It's probably worth emphasizing this sets a maximum width not a fixed size width. – matanster Dec 30 '18 at 13:09
  • This works for the trivial example above, but it is not working for me with a pre-existing dataframe using Pandas v1.4.2. No error information is available showing why the setting does not change. – Rich Lysakowski PhD Apr 21 '22 at 18:57
36

The easiest solution I have found on newer versions of Pandas is outlined in this page of the Pandas reference materials. Search for display.max_colwidth -- about 1/3rd of the way down the page describes how to use it e.g.:

pd.set_option('max_colwidth', 400)

Note that this will set the value for the session, or until changed.

If you only want to make temporary changes see this info on temporarily setting context e.g.:

from pandas import option_context

with option_context('display.max_colwidth', 400):
    display(df.head())

I've not found an obvious way to set individual columns but this approach only scales up those that need more space to the maximum you set.

Also possibly of use if trying to adjust how to fit things on screen/in tables/making space for other columns is pd.set_option('precision', 2) which changes the no of decimal places.

Tom Bush
  • 581
  • 6
  • 11
  • Very useful, complete, memorable, and ready-to-use answer! A nice touch with the `display` (required to pretty-print the table in a context, e.g. of a `for` loop or `with` clause). – mirekphd Feb 23 '22 at 09:11
  • @mirekphd Kind words! Really good point on the reason why `display` is required -- I failed to explain that bit :-) – Tom Bush Feb 23 '22 at 15:07