ignoring_gravity
ignoring_gravity

Reputation: 10511

Dispaly DataFrame in Jupyter Notebook along with other attributes

If I just construct a pandas DataFrame in a Jupyter notebook, then the output looks nice:

frame = pd.DataFrame({'a': [1,2,3]})
frame

enter image description here

However, if I make my own class whose repr is a pandas.DataFrame, then that formatting is lost:

class Foo:
    def __init__(self, frame, bar):
        self.frame = frame
        self.bar = bar
    
    def __repr__(self):
        return repr(self.frame)

enter image description here

How can I define the repr of my class Foo, such that when I display it in a Jupyter Notebook, it'll look just like it would if it was a pandas.DataFrame?

Upvotes: 1

Views: 73

Answers (1)

Wayne
Wayne

Reputation: 9810

You can add a repr_html() method that incorporates what @Atanas Atanasov was suggesting.

class Foo:
    def __init__(self, frame, bar):
        self.frame = frame
        self.bar = bar
    
    def __repr__(self):
        return repr(self.frame)

    def _repr_html_(self):
        return frame.to_html()

Below first shows what the OP report and then shows the addition of repr_html() in the bottom Foo class definition ([4] and [5]) fixes it:

enter image description here

It's like what Pandas uses for _repr_html_ in it's style.py where it says at the top it is the "Module for applying conditional formatting to DataFrames and Series".


The Details

The key resource you seek for guidance in making your class integrate well with Jupyter is covered under items like _repr_html_l and/or _repr_mimebundle_ in the 'Integrating your objects with IPython' section in the documentation.

I dug around in the Pandas code and it looked like it would be here where the `repr_html() is defined for Pandas rendering if dataframes. At the top there it says 'Module for applying conditional formatting to DataFrames and Series.'

See example of use of _repr_mimebundle_ here to make a custom class display latex in a Jupyter notebook rendering.
This answer uses the related _repr_html_() to make a custom class to control how an SVG object is rendered in the running .ipynb file so it remains interactive from scripted details embedded in its encoding file.
Here, the class is having the representational method added, but if you had a lot of functions or classes that were making a distinguishable output you can modify the global displayhook to handle those cases specifically instead of one at a time, see example suggestion here.

Upvotes: 1

Related Questions