Issue
I have a pandas dataframe with textual data and I want to display all texts without truncation so I set
pd.set_option('display.max_colwidth', None)
pd.set_option('display.max_rows', None)
However, the table now doesn't fit my screen, you can see the scroll bar at the bottom of the image appeared. I want to display a dataframe so that in width it fits my screen (i.e. cells can grow in height but not in width).
Solution
This is the solution I found
from IPython.display import display
display(_df.style.set_properties(**{
'width': '230px',
'max-width': '230px'
}))
and I wrote a helper function for this
# decorator
def pandas_display(func):
default_1 = pd.options.display.max_rows
default_2 = pd.options.display.max_colwidth
def wrapper(_df, exclude_cols=None, properties=None, limit_float=2):
pd.options.display.max_rows = 1000
pd.options.display.max_colwidth = None
func(_df, exclude_cols, properties, limit_float)
pd.options.display.max_rows = default_1
pd.options.display.max_colwidth = default_2
return wrapper
@pandas_display
def display_df(self, exclude_cols, properties, limit_float):
if exclude_cols is not None:
if not isinstance(exclude_cols, list):
exclude_cols = list(exclude_cols)
cols = [x for x in self.columns.values if x not in set(exclude_cols)]
self = self[cols]
if not properties:
properties = {
'text-align': 'left',
'white-space': 'pre-wrap',
'word-wrap': 'break-word',
'width': '230px',
'max-width': '230px',
}
a = self.style.set_properties(**properties)
if limit_float is not None:
a.format(thousands=',', precision=limit_float)
display(a)
d = display_df
pd.DataFrame.d = d
which you can call by df.d()
Answered By - Alexander Yalunin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.