Reputation: 8298
If I have a pandas.DataFrame
df
, simply doing
df
in an empty Jupyter notebook cell will render it nicely as a table.
Having a class wrapping around a dataframe, how can I render the underlying dataframe in the same way?
class Wrapper:
def __init__(self, df):
self._df = df
def __repr__(self):
## to_html does not work
return self._df.to_html()
This gives the idea, but to_html
does not seem to be able to do the trick. What could I do?
Upvotes: 2
Views: 1266
Reputation: 653
If I understand the question correctly, you are looking to print the df
as a table when a wrapper object is called? If this is the case, then you could wrap the dataframe's _repr_html_
method.
class Wrapper:
def __init__(self, df):
self._df = df
def _repr_html_(self):
return self._df._repr_html_()
Or alternatively:
class Wrapper:
def __init__(self, df):
self._df = df
self.repr_html = self._df._repr_html_
After creating your object with:
mytable = Wrapper(df)
You can display df
in your notebook as a table by calling mytable
mytable # displays the df
Upvotes: 1