66

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?

0

4 Answers 4

75

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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 Kind words! Really good point on the reason why display is required -- I failed to explain that bit :-)
@TomBush I have mine configured so that's not necessary. Check out How to configure IPython to execute cell blocks the same way as a plain Python REPL does?
@TomBush where is the display() function imported from?
@aeroNotAuto it should be there in Jupyter already but I can't speak to its presence in iPython (edit: it's iPython.core.display) and I doubt it's regular, normal Python.
|
69

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

4 Comments

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.
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.
It does work for me except that width changes the hight of the column; yet, removing **{'width': '300px'} seems to maximize the length of the 'text' column ( for totally new to pandas: you have to substitute 'text' with the name of your column). –
You are the best. You saved me hours of search!!!!
9

The answer involving pd.set_option('max_colwidth', 400) didn't work for me.

However Dataframe.style.set_table_styles() worked for me. Knowing about this is great because we can do many things with it.

E.g.:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(4, 4),
                  columns=['A', 'B', 'C', 'D'])

enter image description here

Now, let's change the width of Column A with df.style.set_table_styles().

df.style.set_table_styles({
    'A': [{'selector': '',
           'props': [('width', '200px')]}],
}, overwrite=False)

enter image description here

Now, let's do some more stuff:

df.style.set_table_styles({
    'A': [{'selector': '',
           'props': [('color', 'red'), ('width', '200px')]}],
    'B': [{'selector': 'td',
           'props': [('color', 'blue')]}]
}, overwrite=False)

enter image description here

We can even do this kind of stuff for multi-index data frames.

import numpy as np
df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]],
                  index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)'], name='Actual Label:'),
                  columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression', 'Random'],['Tumour', 'Non-Tumour']], names=['Model:', 'Predicted:']))
df

enter image description here

Then change table properties

df.style.set_table_styles({
    ('Regression', 'Tumour'): [{'selector': '',
                                'props': [('background-color', '#00aaaa')]},
                            ],
     ('Regression', 'Non-Tumour'): [{'selector': '',
                                'props': [('background-color', '#00aaff'), ('width', '200px')]},
                            ]
}, axis=0)

enter image description here

We can also play with rows.

df.style.set_table_styles([{'selector': 'tr',
                                'props': [('line-height', '40px')]},
                            ], axis=1)

enter image description here

Comments

1

Here is what worked for me:

Keep in mind, replace the payload with your data.

payload = {'col1': 'col1', 'col2': 'col2'}

df = pd.DataFrame(payload)

response = HttpResponse(content_type='application/xlsx')
response['Content-Disposition'] = f'attachment; filename="{filename}.xlsx"'
with pd.ExcelWriter(response) as writer:
    df.to_excel(writer, sheet_name=f'worksheet_name', index=False)
    # Manually adjust the width of column
    for column in df:
        column_width = max(df[column].astype(str).map(len).max(), len(column))
        col_idx = df.columns.get_loc(column)
        writer.sheets[f'worksheet_name'].set_column(col_idx, col_idx, column_width)

return response

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
this is nice, but the question doesn't involve or mention excel in any way, hence the lack of upvotes on your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.