This notebook provides an example of using proxy widgets to update a segment of HTML in place inside a notebook. In this case we create a table using javascript and provide a method to update the table.
Afterwards we can call the method with new data and the table updates in place in the notebook.
# Make some test data:
headers = "Eenie Meanie Miney".split()
rows = []
for i in range(4):
row = []
for j in range(3):
row.append((i+1)*(j+2))
rows.append(row)
headers, rows
# Create a proxy widget with a table update method
import jp_proxy_widget
def updateable_table(headers, rows):
w = jp_proxy_widget.JSProxyWidget()
w.js_init("""
element.update_table = function(headers, rows) {
element.empty();
var table = $("<table border style='text-align:center'/>");
table.appendTo(element);
var header_row = $("<tr/>");
for (var i=0; i<headers.length; i++) {
$("<th style='text-align:center'>" + headers[i] + "</th>")
.width(50)
.appendTo(header_row);
}
header_row.appendTo(table);
for (var j=0; j<rows.length; j++) {
var table_row = $("<tr/>").appendTo(table);
var data_row = rows[j];
for (var i=0; i<data_row.length; i++) {
$("<td>" + data_row[i] + "</td>").appendTo(table_row);
}
}
}
element.update_table(headers, rows);
""", headers=headers, rows=rows)
return w
# show the widget
w = updateable_table(headers, rows)
w
# Update the widget 20 times
import time
count = -20
for i in range(21):
time.sleep(1)
rows = [rows[-1]] + rows[:-1] # rotate the rows
rows[0][0] = count # change the upper left entry.
count += 1
w.element.update_table(headers, rows)
When first displayed the table looks like this:
When we run the updates the table changes in place 21 times and ultimately looks like this:
It is easy to do the same in place update with pandas
import pandas as pd
import numpy as np
numbers = (100 * np.random.randn(8, 4)).astype(np.int)
columns = "eenie meenie miney moe".split()
df = pd.DataFrame(numbers, columns=columns)
headers = list(df.columns)
rows = df.values.tolist()
w = updateable_table(headers, rows)
w
# update the dataframe and redisplay the table 15 times
import time
count = 0
for i in range(15):
df.values[:] = (100 * np.random.randn(8, 4)).astype(np.int)
df.values[0,0] = i
headers = list(df.columns)
rows = df.values.tolist()
w.element.update_table(headers, rows)
time.sleep(1)