✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

How to create and filter a new datatable by clicking a value in a different datatable in Dash

As the title states I want it so when you’re given the result of a table you can click within a specific column and it will pop up a new table based on what you clicked from the previous table.

So the current code snippet gives you two inputs that allows you to filter the dateframe, and it will give you the resulting datatable. I want it so when you click on something in COL3 it will create a new datatable and filter the df down to include everything that has the value you clicked in COL3.

Current basic example of just the first datatable I have

For example in the table shown above if someone were to click ‘C’ in COL3 it would redo the filter or give you a new table and give you all the entries that has ‘C’ in COL3

Code:

import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output


important_cols = ['COL1', 'COL2', 'COL3', 'COL4' ]
df = df_mat[important_cols].copy()
df.drop_duplicates(inplace=True)
PAGE_SIZE = 20
	

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
	dcc.Input(value='', id='col1_input', placeholder='COL1', debounce=False, required=True),
	dcc.Input(value='', id='col2_input', placeholder='COL2', debounce=True, required=False),
	dash_table.DataTable(
		id='datatable-paging',
		columns=[
			{"name": i, "id": i} for i in df.columns  # sorted(df.columns)
		],
		page_current=0,
		page_size=PAGE_SIZE,
		page_action='custom',

		sort_action='custom',
		sort_mode='single',
		sort_by=[]
	)
])


@app.callback(
	Output('datatable-paging', 'data'),
	[Input('datatable-paging', 'page_current'),
	 Input('datatable-paging', 'page_size'),
	 Input('datatable-paging', 'sort_by'),
	 Input('col1_input', 'value'),
	 Input('col2_input', 'value'),])
def update_table(page_current, page_size, sort_by, col1_input, col2_input):
	# Filter by col1 and col2. Checks to see if both are inputed or just col1
	if col1_input and col2_input:
		dff = df.loc[(df['COL1'] == col1_input) & (df['COL2'] == col2_input)]
	else:
		dff = df.loc[(df['COL1'] == col1_input)].drop_duplicates(subset=['COL3', 'COL4'])
		
#     Sort if necessary
	if len(sort_by):
		dff = dff.sort_values(
			sort_by[0]['column_id'],
			ascending=sort_by[0]['direction'] == 'asc',
			inplace=False
		)

	return dff.iloc[
		   page_current * page_size:(page_current + 1) * page_size
		   ].to_dict('records')