7

How can I limit the column width within Pandas when displaying dataframes, etc? I know about display.max_colwidth but it doesn't affect column names. Also, I do not want to break the names up, but rather to truncate.

If I set display.max_colwidth it sure enough limits the values, and shortens them with the ellipsis, but the column names remain long and unaffected. I don't see this mentioned anywhere in the documentation and didn't see it in the big threads here or here. Is it a bug? I know I could truncate the columns' names, but I want them long otherwise, just shortened when displaying.

Just to be clear this is what's happening:

Before

     State area_harveste_2016_1000_acres area_harvested_2017_1000_acres yield_per_acr_2016_bushels yield_per_acre_2017_bushels
4  Alabama                           315                            235                      120.0                       165.0

Change the width

pd.set_option("display.max_colwidth",5)

After

   State area_harveste_2016_1000_acres area_harvested_2017_1000_acres yield_per_acr_2016_bushels yield_per_acre_2017_bushels
4   A...   315                           235                           1...                       1...

Update

Currently this is a confirmed issue with Pandas (as of 20.3 with issues #7059 and #16911. Until resolved, I wrote a work around, which sets and unsets max_colwidth as well as truncates with rename. I couldn't have done it though without the answers from this similar question

def pf(df, L=15):
    """Limit ENTIRE column width (including header)"""
    O = pd.get_option("display.max_colwidth")
    pd.set_option("display.max_colwidth", L)
    print(df.rename(columns=lambda x: x[:L - 3] + '...' if len(x) > L else x))
    pd.set_option("display.max_colwidth", O)
ehiller
  • 1,346
  • 17
  • 32
  • Possible duplicate of [pandas display: truncate column display rather than wrapping](https://stackoverflow.com/questions/45043968/pandas-display-truncate-column-display-rather-than-wrapping) – Brad Solomon Aug 25 '17 at 15:24
  • @BradSolomon - Those answers certainly provide some workarounds - Not actual solutions, the post didn't come up when I was looking around - now that I know others are fighting the same I found two tickets on GitHub regarding this - if others want to track as well: [#7059](https://github.com/pandas-dev/pandas/issues/7059) and [#16911](https://github.com/pandas-dev/pandas/issues/16911) – ehiller Aug 25 '17 at 21:48

1 Answers1

0

You can use Pandas Styler which enables the setting of CSS properties for the HTML display of the dataframes:

dfs = df.style.set_table_styles([dict(selector="th", props=[('max-width', '120px'),
                                ('text-overflow', 'ellipsis'), ('overflow', 'hidden')])])
display(dfs)

th is for the table header, for the rest of the table data it's td instead.

rehaqds
  • 414
  • 2
  • 6