Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

temporarily change pandas’ set_option for displaying dataframe

Tags:

python

pandas

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?

like image 392
steven Avatar asked Mar 05 '23 08:03

steven


1 Answers

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

like image 172
piRSquared Avatar answered Mar 08 '23 22:03

piRSquared