Skip to content

Instantly share code, notes, and snippets.

@tommct
Created June 11, 2022 22:32
Show Gist options
  • Save tommct/2464f2882a13fa45181a112d19157730 to your computer and use it in GitHub Desktop.
Save tommct/2464f2882a13fa45181a112d19157730 to your computer and use it in GitHub Desktop.
Update the display of a Pandas DataFrame interactively in a Jupyter Notebook using Jupyter Widgets
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "0e6ce9c1",
"metadata": {},
"source": [
"This notebook illustrates how [Jupyter Widgets](https://ipywidgets.readthedocs.io/en/latest/) can update and display parts of a [Pandas](https://pandas.pydata.org/) DataFrame."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "certified-prospect",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"from IPython.display import HTML\n",
"from ipywidgets import widgets, HBox, Dropdown, IntSlider\n",
"\n",
"df = pd.DataFrame(np.arange(5*3).reshape(5,3), columns=['a', 'b', 'c'])\n",
"df['c'] = df['c'].values[::-1]"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4e8b43e3",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "e699e20066ea4a28a864b6ef2c686a78",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"HBox(children=(Dropdown(description='Column to sort:', layout=Layout(width='initial'), options=('a', 'b', 'c')…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "f257ea17c1324120b5e8a97fad1044eb",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"style = {'description_width': 'initial'}\n",
"\n",
"col = Dropdown(\n",
" options=df.columns,\n",
" description='Column to sort:',\n",
" style=style,\n",
" layout=widgets.Layout(width='initial')\n",
")\n",
"\n",
"asc = Dropdown(\n",
" options=[True, False],\n",
" description='Ascending:',\n",
" style=style,\n",
" layout=widgets.Layout(width='initial')\n",
")\n",
"\n",
"c3 = IntSlider(\n",
" value=5,\n",
" min=0,\n",
" max=20,\n",
" description='Index <b>3</b>, Column <b>c</b> value:',\n",
" style=style,\n",
" layout=widgets.Layout(width='300px', padding='0px 0px 0px 20px')\n",
")\n",
"\n",
"hbox = widgets.HBox([col, asc, c3], layout=widgets.Layout(width='100%'))\n",
"\n",
"def update_df(df, col, asc, c3):\n",
" df.loc[3, 'c'] = c3\n",
" if col == 'b':\n",
" # To show dynamical output of size, we'll omit the last row and 'a' if sorting on 'b'\n",
" display(HTML(df[['b', 'c']].sort_values(by=col, ascending=asc).iloc[:-1].to_html()))\n",
" return\n",
" display(HTML(df.sort_values(by=col, ascending=asc).to_html()))\n",
" \n",
"out = widgets.interactive_output(\n",
" update_df, \n",
" dict(\n",
" df=widgets.fixed(df), # use widgets.fixed for passing in non-interactive args\n",
" col=col, \n",
" asc=asc, \n",
" c3=c3\n",
" )\n",
")\n",
"\n",
"display(hbox)\n",
"display(out)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "distributed-nowhere",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"hide_input": false,
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment