Skip to content

Instantly share code, notes, and snippets.

@bollwyvl
Last active August 29, 2015 14:05
Show Gist options
  • Save bollwyvl/6ad208084744c60dda65 to your computer and use it in GitHub Desktop.
Save bollwyvl/6ad208084744c60dda65 to your computer and use it in GitHub Desktop.
Updated IPython/Handsontable Integration
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"celltoolbar": "Widget Editing",
"kernelspec": {
"codemirror_mode": {
"name": "python",
"version": 2
},
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"name": "",
"signature": "sha256:ef21e0407cd5fcf02ba69c5cc4131dc8b223144582301bc77b938042df4a79b6"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"> # _Updated_\n",
"> Based on [this issue](https://github.com/handsontable/jquery-handsontable/issues/1666).\n",
"\n",
"> [Visit the original](http://nbviewer.ipython.org/gist/rossant/9463955#).\n",
"\n",
"> Changes:\n",
" - loading up the dependencies (JS, CSS) from the HoT site directly without mucking about with `custom.js`. There are better ways to do this: [`install_nbextension`](https://github.com/ipython/ipython/blob/master/IPython/html/nbextensions.py), etc.\n",
" - dealing with the keyboard manager for the [modal interface](http://ipython.org/ipython-doc/dev/whatsnew/version2.0.html#modal-user-interface)\n",
" - using the HoT API where possible, instead of relying on underlying jQuery or backbone behavior (which could change withouit warning, apparently)"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%html\n",
"<style>@import url(\"http://handsontable.com/dist/jquery.handsontable.full.css\")</style>"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"outputs": [
{
"html": [
"<style>@import url(\"http://handsontable.com/dist/jquery.handsontable.full.css\")</style>"
],
"metadata": {},
"output_type": "display_data",
"text": [
"<IPython.core.display.HTML object>"
]
}
],
"prompt_number": 272
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"# Excel-like data grid editor for Pandas in the IPython notebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"This proof-of-concept brings an **interactive Excel-like data grid editor** in the IPython notebook, compatible with Pandas' *DataFrame*. It means that whenever you have a *DataFrame* in the IPython notebook, you can edit it within an integrated GUI in the notebook, and the corresponding Python object will be automatically updated in real-time."
]
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"This proof-of-concept uses the new widget machinery of IPython 2.0. You need the latest development version of IPython (or v2.0beta, or v2.0 when it's released within the next few weeks). You also need the [Handsontable](http://handsontable.com/) Javascript library. Other data grid editors could probably be used as well."
]
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"## Getting started"
]
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"There are multiple steps to make this example work (assuming you have the latest IPython).\n",
"\n",
"1. Go [here](https://github.com/warpech/jquery-handsontable/tree/master/dist).\n",
"2. Download `jquery.handsontable.full.css` and `jquery.handsontable.full.js`, and put these two files in `~\\.ipython\\profile_default\\static\\custom\\`.\n",
"3. In this folder, add the following line in `custom.js`:\n",
"```javascript\n",
"require(['/static/custom/jquery.handsontable.full.js']);\n",
"```\n",
"4. In this folder, add the following line in `custom.css`:\n",
"```css\n",
"@import \"/static/custom/jquery.handsontable.full.css\"\n",
"```\n",
"5. Execute this notebook."
]
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"## How to do it..."
]
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"* Let's import a few functions and classes."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from __future__ import print_function # For py 2.7 compat\n",
"\n",
"from IPython.html import widgets # Widget definitions\n",
"from IPython.display import display # Used to display widgets in the notebook\n",
"from IPython.utils.traitlets import List, Dict # Used to declare attributes of our widget"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"outputs": [],
"prompt_number": 273
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"* We create a new widget. The `value` trait will contain the JSON representation of the entire table. This trait will be synchronized between Python and Javascript by IPython 2.0's widget machinery."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class HandsonTableWidget(widgets.DOMWidget):\n",
" _view_name = Unicode('HandsonTableView', sync=True)\n",
" value = Unicode(sync=True)\n",
" settings = Dict(sync=True)"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"outputs": [],
"prompt_number": 274
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"* Now we write the Javascript code for the widget. There is a tiny bit of boilerplate code, but have a look at the three important functions that are responsible for the synchronization:\n",
"\n",
" * `render` for the widget initialization\n",
" * `update` for Python --> JS update\n",
" * `handle_table_change` for JS --> Python update\n",
"\n",
"This is a bit oversimplified, of course. You will find more information on this [tutorial](http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/widgets/Part%206%20-%20Custom%20Widget.ipynb)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%javascript\n",
";(function(require){\n",
" \"use strict\";\n",
" var window = this;\n",
" require([\n",
" \"base/js/namespace\",\n",
" \"widgets/js/manager\",\n",
" \"widgets/js/widget\",\n",
" \"underscore\",\n",
" \"jquery\",\n",
" \"http://handsontable.com/dist/jquery.handsontable.full.js\"\n",
" ], function(IPython, manager, widget, _, $){\n",
" // Just once, ensure that the scroll event is called on the window for HoT\n",
" var $win = $(window);\n",
" IPython.notebook.element.on(\"scroll\", function(){ $win.scroll(); });\n",
"\n",
" // Define the HandsonTableView\n",
" var HandsonTableView = widget.DOMWidgetView.extend({\n",
"\n",
" render: function(){\n",
" // CREATION OF THE WIDGET IN THE NOTEBOOK.\n",
" // Add a <div> in the widget area.\n",
" this.$table = $('<div />').appendTo(this.$el);\n",
" \n",
" var view = this;\n",
"\n",
" // Create the Handsontable table.\n",
" this.$table.handsontable({\n",
" // when working in HoT, don't listen for command mode keys\n",
" afterSelection: function(){ IPython.keyboard_manager.disable(); },\n",
" afterDeselect: function(){ IPython.keyboard_manager.enable(); },\n",
" // the data changed. `this` is the HoT instance\n",
" afterChange: function(changes, source){\n",
" // don't update if we did the changing!\n",
" if(source === \"loadData\"){ return; }\n",
" view.handle_table_change(this.getData());\n",
" }\n",
" });\n",
" },\n",
"\n",
" update: function() {\n",
" // PYTHON --> JS UPDATE.\n",
"\n",
" // Get the model's value (JSON)\n",
" var json = this.model.get('value');\n",
" \n",
" // Parse it into data (list of lists)\n",
" var data = JSON.parse(json);\n",
" \n",
" // Give it to the Handsontable widget.\n",
" this.$table.handsontable({data: data});\n",
" \n",
" // Don't touch this...\n",
" return HandsonTableView.__super__.update.apply(this);\n",
" },\n",
"\n",
" handle_table_change: function(data) {\n",
" // JS --> PYTHON UPDATE.\n",
" // Update the model with the JSON string.\n",
" this.model.set('value', JSON.stringify(data));\n",
"\n",
" // Don't touch this...\n",
" this.touch();\n",
" }\n",
" });\n",
" // Register the HandsonTableView with the widget manager.\n",
" manager.WidgetManager.register_widget_view('HandsonTableView', HandsonTableView);\n",
" });\n",
"}).call(this, require);"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {},
"enabled": true
}
},
"outputs": [
{
"javascript": [
";(function(require){\n",
" \"use strict\";\n",
" var window = this;\n",
" require([\n",
" \"base/js/namespace\",\n",
" \"widgets/js/manager\",\n",
" \"widgets/js/widget\",\n",
" \"underscore\",\n",
" \"jquery\",\n",
" \"http://handsontable.com/dist/jquery.handsontable.full.js\"\n",
" ], function(IPython, manager, widget, _, $){\n",
" // Just once, ensure that the scroll event is called on the window for HoT\n",
" var $win = $(window);\n",
" IPython.notebook.element.on(\"scroll\", function(){ $win.scroll(); });\n",
"\n",
" // Define the HandsonTableView\n",
" var HandsonTableView = widget.DOMWidgetView.extend({\n",
"\n",
" render: function(){\n",
" // CREATION OF THE WIDGET IN THE NOTEBOOK.\n",
" // Add a <div> in the widget area.\n",
" this.$table = $('<div />').appendTo(this.$el);\n",
" \n",
" var view = this;\n",
"\n",
" // Create the Handsontable table.\n",
" this.$table.handsontable({\n",
" // when working in HoT, don't listen for command mode keys\n",
" afterSelection: function(){ IPython.keyboard_manager.disable(); },\n",
" afterDeselect: function(){ IPython.keyboard_manager.enable(); },\n",
" // the data changed. `this` is the HoT instance\n",
" afterChange: function(changes, source){\n",
" // don't update if we did the changing!\n",
" if(source === \"loadData\"){ return; }\n",
" view.handle_table_change(this.getData());\n",
" }\n",
" });\n",
" },\n",
"\n",
" update: function() {\n",
" // PYTHON --> JS UPDATE.\n",
"\n",
" // Get the model's value (JSON)\n",
" var json = this.model.get('value');\n",
" \n",
" // Parse it into data (list of lists)\n",
" var data = JSON.parse(json);\n",
" \n",
" // Give it to the Handsontable widget.\n",
" this.$table.handsontable({data: data});\n",
" \n",
" // Don't touch this...\n",
" return HandsonTableView.__super__.update.apply(this);\n",
" },\n",
"\n",
" handle_table_change: function(data) {\n",
" // JS --> PYTHON UPDATE.\n",
" // Update the model with the JSON string.\n",
" this.model.set('value', JSON.stringify(data));\n",
"\n",
" // Don't touch this...\n",
" this.touch();\n",
" }\n",
" });\n",
" // Register the HandsonTableView with the widget manager.\n",
" manager.WidgetManager.register_widget_view('HandsonTableView', HandsonTableView);\n",
" });\n",
"}).call(this, require);"
],
"metadata": {},
"output_type": "display_data",
"text": [
"<IPython.core.display.Javascript object>"
]
}
],
"prompt_number": 275
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"* Now, we have a synchronized table widget that we can already use. But we'd like to integrate it with Pandas. To do this, we create a light wrapper around a `DataFrame` instance. We create two callback functions for synchronizing the Pandas object with the IPython widget. Changes in the GUI will automatically trigger a change in the `DataFrame`, but the converse is not true. You'll need to re-display the widget if you change the `DataFrame` in Python."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import StringIO\n",
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"class HandsonDataFrame(object):\n",
" def __init__(self, df):\n",
" self._df = df\n",
" self._widget = HandsonTableWidget()\n",
" self._widget.on_trait_change(self._on_data_changed, 'value')\n",
" self._widget.on_displayed(self._on_displayed)\n",
" \n",
" def _on_displayed(self, e):\n",
" # DataFrame ==> Widget (upon initialization only)\n",
" json = self._df.to_json(orient='values')\n",
" self._widget.value = json\n",
" \n",
" def _on_data_changed(self, e, val):\n",
" # Widget ==> DataFrame (called every time the user\n",
" # changes a value in the graphical widget)\n",
" buf = StringIO.StringIO(val)\n",
" self._df = pd.read_json(buf, orient='values')\n",
" \n",
" def to_dataframe(self):\n",
" return self._df\n",
" \n",
" def show(self):\n",
" display(self._widget)"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"outputs": [],
"prompt_number": 276
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"* Now, let's test all that! We first create a random `DataFrame`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"data = np.random.randint(size=(3, 5), low=100, high=900)\n",
"df = pd.DataFrame(data)\n",
"df"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"outputs": [
{
"html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>0</th>\n",
" <th>1</th>\n",
" <th>2</th>\n",
" <th>3</th>\n",
" <th>4</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td> 175</td>\n",
" <td> 339</td>\n",
" <td> 184</td>\n",
" <td> 125</td>\n",
" <td> 620</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 106</td>\n",
" <td> 828</td>\n",
" <td> 493</td>\n",
" <td> 673</td>\n",
" <td> 329</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 310</td>\n",
" <td> 479</td>\n",
" <td> 784</td>\n",
" <td> 109</td>\n",
" <td> 392</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"metadata": {},
"output_type": "pyout",
"prompt_number": 277,
"text": [
" 0 1 2 3 4\n",
"0 175 339 184 125 620\n",
"1 106 828 493 673 329\n",
"2 310 479 784 109 392"
]
}
],
"prompt_number": 277
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"* We wrap it in a `HandsonDataFrame` and show it."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"ht = HandsonDataFrame(df)\n",
"ht.show()"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"outputs": [],
"prompt_number": 288
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"We can now *change* the values interactively, and they will be changed in Python automatically."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"ht.to_dataframe()"
],
"language": "python",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"outputs": [
{
"html": [
"<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>0</th>\n",
" <th>1</th>\n",
" <th>2</th>\n",
" <th>3</th>\n",
" <th>4</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td> 175</td>\n",
" <td> 339</td>\n",
" <td> 184</td>\n",
" <td> 125</td>\n",
" <td> 620</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td> 106</td>\n",
" <td> 828</td>\n",
" <td> 493</td>\n",
" <td> 673</td>\n",
" <td> 329</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td> 310</td>\n",
" <td> 479</td>\n",
" <td> 784</td>\n",
" <td> 109</td>\n",
" <td> 392</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"metadata": {},
"output_type": "pyout",
"prompt_number": 286,
"text": [
" 0 1 2 3 4\n",
"0 175 339 184 125 620\n",
"1 106 828 493 673 329\n",
"2 310 479 784 109 392"
]
}
],
"prompt_number": 286
},
{
"cell_type": "markdown",
"metadata": {
"widgedit": {
"cm_options": {}
}
},
"source": [
"There are many ways this proof-of-concept could be improved.\n",
"\n",
"* Synchronize only deltas instead of synchronizing the whole array every time (i.e. the method here would be slow on large tables).\n",
"* Also, avoid recreating a new `DataFrame` at very change, but update the same `DataFrame` instance in-place.\n",
"* Support for named columns.\n",
"* Hide the wrapper, i.e. make it so that the default rich representation of the `DataFrame` in the notebook is the `HandsonDataFrame`.\n",
"* Implement everything in an easy-to-use extension.\n",
"* etc."
]
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment