steven
steven

Reputation: 2519

temporarily change pandas’ set_option for displaying dataframe

I'm using Jupyter notebook and imported many DataFrames and one of them contains very long strings. Thus, I'd like to temporarily change pandas' display option without affect the global setting. I tried to use with:

with pd.set_option('display.max_colwidth', 220): 
    df.head()

But it doesn't work and returns AttributeError: __enter__.

Am I missing something?

Upvotes: 8

Views: 3348

Answers (1)

piRSquared
piRSquared

Reputation: 294488

pandas.option_context

with pd.option_context('display.max_colwidth', 220):
  print(df.head())

Consider d1

d1 = pd.DataFrame(dict(A=['brown', 'blue', 'blue'*20]))

print(d1)

                                                   A
0                                              brown
1                                               blue
2  bluebluebluebluebluebluebluebluebluebluebluebl...

You can see the column width is not long enough

with pd.option_context('display.max_colwidth', 220):
  print(d1.head())                                                           

    A
0                                                                             brown
1                                                                              blue
2  blueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblue

To show the HTML

from IPython.display import display, HTML

with pd.option_context('display.max_colwidth', 220):
  display(HTML(d1.to_html()))

enter image description here

Upvotes: 14

Related Questions