From a Python dataframe to Javascript within Ipython Notebook

I was willing to pass on data contained in a quite big dataframe  — specifically in a pandas.DataFrame object (Python) — to Javascript.

I couldn’t find any straightforward reply on the internet, but came across websites saying there is no easy way to have Python and Javascript working together within IPython notebook due to security reasons.

After a couple of hours (more) banging my head against the wall, I finally came up with the following solution (see code below). It is surely not that smart (it roughly consists on converting the original dataframe in some string that will be converted back to some structured format in Javascript), but that works. ‘First, make it work’, so ….

Just below is the Python part, in a cell of the notebook:

# Required library
import pandas as pd
from IPython.html import widgets

# Create an example pandas DataFrame object
df = pd.DataFrame([{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}], index=['first', 'second'])

# Convert df to json
jdf = df.to_json(orient='records')

# Create a Ipython widget
widgets.HTMLWidget(
    value='''<div  class='dataframe'> ''' + jdf + '</div>'  # One can add 'hidden' argument to the div tag
                                                            # while original dataframe becomes cumbersome
)

In another cell, one can check the data originally produced in Python are actually available to Javascript as json object:

%%javascript // This notebook cell deals with Javascript

// Get the data jsoned dataframe (actually it is a mere string ...) 
var jadf = $('div.dataframe').text();

// Convert to json usable in Javascript
var obj = jQuery.parseJSON(jadf);

// Check Javascript interprets obj as a json object 
$.each(obj, function(index, element) {
    console.log(element.second); 
});

And, that’s it…