1

I'm trying to display a column based on the user's input. For example, columns 2 and 3 are not displayed, but if the user types 2, column 2 will be displayed. However, my current program is displaying both columns even if the only input is 2 and I'm not sure why. Is there an issue with the callback?

data = {"1": [1, 2, 3, 4, 5], "2": [6, 7, 8, 9, 10], "3": [11, 12, 13, 14, 15]}
hide_cols = ["2", "3"]

df = pd.DataFrame(data)

app.layout = html.Div(
    [
        "Choose Column to Show: ",
        dcc.Input(id="show_col", type="text", placeholder="", debounce=True),
        html.Br(),
        dash_table.DataTable(
            id="df",
            columns=[{"name": i, "id": i} for i in df.columns],
            data=df.to_dict("records"),
            row_deletable=True,
        ),
    ]
)


@app.callback(Output("df", "style_data_conditional"), Input("show_col", "value"))
def show_column_data(value):
    if value is not None and value in hide_cols:
        return [{"if": {"column_id": value}, "display": ""}]
    else:
        return [{"if": {"column_id": hide_cols}, "display": "None"}]


@app.callback(Output("df", "style_header_conditional"), Input("show_col", "value"))
def show_column_header(value):
    if value is not None and value in hide_cols:
        return [{"if": {"column_id": value}, "display": ""}]
    else:
        return [{"if": {"column_id": hide_cols}, "display": "None"}]


if __name__ == "__main__":
    app.run_server(debug=True)

Before user input

After user input

Crystal
  • 11
  • 3

1 Answers1

0

Never mind! I managed to figure it out, I just had to add another style_data_conditional and style_header_conditional that keeps the extra columns hidden:

@app.callback(Output("df", "style_data_conditional"), Input("show_col", "value"))
def show_column_data(value):
    if value is not None and value in hide_cols:
        index = hide_cols.index(value)
        keep_hidden = hide_cols[:index] + hide_cols[index + 1 :]

        return [{"if": {"column_id": value}, "display": ""}] + [{"if": {"column_id": keep_hidden}, "display": "None"}]
    else:
        return [{"if": {"column_id": hide_cols}, "display": "None"}]


@app.callback(Output("df", "style_header_conditional"), Input("show_col", "value"))
def show_column_header(value):
    if value is not None and value in hide_cols:
        index = hide_cols.index(value)
        keep_hidden = hide_cols[:index] + hide_cols[index + 1 :]

        return [{"if": {"column_id": value}, "display": ""}] + [{"if": {"column_id": keep_hidden}, "display": "None"}]
    else:
        return [{"if": {"column_id": hide_cols}, "display": "None"}]
Crystal
  • 11
  • 3