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)