Let’s suppose that I want to make a Dash app call from a python class, within a jupyter notebook/lab (hence using jupyter_dash), do some stuffs and finally access to the modified object.
I am currently falling short on this last task and couldn’t make it work in any way. Here a minimal working example:
import pandas as pd
import numpy as np
from flask import Flask
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
from dash import html, dcc
from jupyter_dash import JupyterDash
# Initialize flask server and dash app
server = Flask(__name__)
app = JupyterDash(
__name__,
server=server,
external_stylesheets=[
dbc.themes.BOOTSTRAP,
],
)
class DropCol:
def __init__(self, server, app, mode="inline", debug=True):
self.mode = mode
self.debug = debug
self.app = app
self.server = server
self.callbacks(self.app)
def __call__(self, df: pd.DataFrame):
# Create layout based on dataframe
col_options = [{"label": c, "value": c} for c in df.columns]
data_store = dcc.Store(id="data-store", data=df.to_json(date_format="iso", orient="split"))
dropdown = dcc.Dropdown(id="cols", options=col_options)
self.app.layout = html.Div(
id="layout",
children=[
data_store,
dropdown
],
)
# run the app
self.app.run_server(mode=self.mode, debug=self.debug, port="8000")
def callbacks(self, app):
"""Initialize app callbacks"""
@app.callback(
Output("data-store", "data"),
Input("cols", "value"),
State("data-store", "data"),
prevent_initial_call=True,
)
def on_col_selection(col_name, df_jsonified):
df = (pd.read_json(df_jsonified, orient="split")
.drop(col_name, axis=1)
)
return df.to_json(date_format="iso", orient="split")
@property
def get_data_frame(self):
"""property to retrieve dataframe from data-store"""
df_json = self.app.layout['data-store'].data
return pd.read_json(df_json, orient="split")
# Sample dataframe
df = pd.DataFrame({
"a": np.arange(10),
"b": np.random.randn(10)
})
col_dropper = DropCol(server, app, mode="inline")
col_dropper(df)
"""
Here I select one of the column from the dropdown, hence I expect that the json `data-store` has one column remaining.
However this is not the case when I access the data in the following cell
"""
col_dropper.get_data_frame.head(3)
| | a | b |
|---:|----:|----------:|
| 0 | 0 | 1.0964 |
| 1 | 1 | -0.30562 |
| 2 | 2 | 1.34761 |
As you can see, the stored dataframe I am able to access has all the columns, even after I select one in the above call.
Suppose that I select column b
, then the expected output is:
col_dropper.get_data_frame.head(3)
| | a |
|---:|----:|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
Packages versions I am using are: dash==2.0.0, dash_bootstrap_components==1.0.1, flask==2.0.1, jupyter_dash==0.4.0
Is there any way to accomplish such task?