Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set variable column widths in pandas?

Tags:

python

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?

like image 795
scrollex Avatar asked Sep 24 '16 19:09

scrollex


People also ask

How do I increase column width in pandas?

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.

How do you dynamically adjust column width in Excel?

Select the column or columns that you want to change. On the Home tab, in the Cells group, click Format. Under Cell Size, click AutoFit Column Width. Note: To quickly autofit all columns on the worksheet, click the Select All button, and then double-click any boundary between two column headings.

How do I set column width in Python?

Setting the Column Width Set the width of a column by calling the Cells collection's setColumnWidth method. The setColumnWidth method takes the following parameters: Column index, the index of the column that you're changing the width of. Column width, the desired column width.


2 Answers

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

like image 142
Romain Avatar answered Oct 22 '22 04:10

Romain


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.

like image 43
Tom Bush Avatar answered Oct 22 '22 03:10

Tom Bush