How to limit width of column headers in Pandas

2024/10/10 4:27:06

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)
Answer

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.

https://en.xdnf.cn/q/69933.html

Related Q&A

Django + Auth0 JWT authentication refusing to decode

I am trying to implement Auth0 JWT-based authentication in my Django REST API using the django-rest-framework. I know that there is a JWT library available for the REST framework, and I have tried usin…

How to measure the angle between 2 lines in a same image using python opencv?

I have detected a lane boundary line which is not straight using hough transform and then extracted that line separately. Then blended with another image that has a straight line. Now I need to calcula…

How to modify variables in another python file?

windows 10 - python 3.5.2Hi, I have the two following python files, and I want to edit the second files variables using the code in the first python file.firstfile.pyfrom X.secondfile import *def edit(…

SciPy optimizer ignores one of the constraints

I am trying to solve an optimization problem where I need to create a portfolio that with a minimum tracking error from benchmark portfolio and its subject to some constraints:import scipy.optimize as …

How can one use HashiCorp Vault in Airflow?

I am starting to use Apache Airflow and I am wondering how to effectively make it use secrets and passwords stored in Vault. Unfortunately, search does not return meaningful answers beyond a yet-to-be-…

List all words in a dictionary that start with user input

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?Ex: User: "abd" Program:abdicate, abdomen, abduct..…

Python version of C#s conditional operator (?)

I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test.I have this code in Python:if self.trait == self.spouse.trait:trait = self.trait else:trait…

Python String Replace Error

I have a python script that keeps returning the following error:TypeError: replace() takes at least 2 arguments (1 given)I cannot for the life of me figure out what is causing this.Here is part of my c…

How to run two modules at the same time in IDLE

I am working on a super simple socket program and I have code for the client and code for the server. How do I run both these .py files at the same time to see if they work ?

Passing 2 dimensional C array to python numpy

I need some help regarding passing C array to python(numpy). I have 2d array of doubles NumRows x NumInputs, it seems that PyArray_SimpleNewFromData does not convert it right way - it is hard to see be…