Here is an example where each row in the dataframe has a clickable link which triggers a call to the regular python function select_row
. The function is defined, currently, to set a global variable selection
to the clicked row number, though the function can be defined differently.
To achieve this, the dataframe is embedded in custom html. I used this link for help with the Javascript.
import pandas as pd
from IPython.display import HTML as ipyhtml
# function for selecting a row
def select_row(row:'int'):
global selection
selection = row
return
Defining the dataframe and interactivity in js + html
# define the dataframe
df = pd.DataFrame(data=dict(Name=['Mary', 'Bruce', 'Emma'], Score=[10,6,8]))
# add links as column into df, each with a unique id `mylink<row>`
# href = '#' does no redirecting in the browser
df['Select'] = [
'<a id="mylink%s" href="#">Select</a>' % i for i in range(len(df))
]
# generate javascript <script>
js_script = """<script type="text/javascript">"""
for i in range(len(df)):
js_script+="""
// get a reference to each link "mylink<row>"
var a%s = document.getElementById("mylink%s");
// specify an "onclick" function for each link
a%s.onclick = function() {
// run the python function "select_row(<row>)"
Jupyter.notebook.kernel.execute(`select_row(%s)`)
return false;
}
""" % (i, i, i, i)
js_script+="""\n</script>"""
# generate the final html
selectable_df_html = """
<html>
<head>
%s
</head>
<body>
%s
</body>
</html>
""" % (js_script, df.style.to_html())
To display the df:
ipyhtml(selectable_df_html)
Clicking any row's "Select" button will set the global variable selection
to that row number