Black Lives Matter. Please consider donating to Black Girls Code today.

Output content of second column using drop down selection of first column

Please Help awesome people! i am new to Dash and trying my best to figure it all out.

I need to use a drop down where I select a state (example: California) and output a statement saying your selection is California and Number of Solar Plants are 289 (which is column 2 of the table).

Here is my code until now:

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

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
available_indicators = df['State'].unique()

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

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

app.layout = html.Div([
    dcc.Dropdown(id='my-dropdown',
       options=[{'label': i, 'value': i} for i in available_indicators],
       value='Texas'),
     html.Div(id='dd-output-container'),
])

@app.callback(
    dash.dependencies.Output('dd-output-container', 'children'),
    [dash.dependencies.Input('my-dropdown', 'value')])
def update_output(value):
    return 'You have selected "{}"'.format(value)

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

Kindly suggest. I will keep trying too in the meantime. Thanks!

Hi @deebratforlife, this is actually more a Pandas question than a Dash question ;-). You want to select the row which as a given value for State and get its value for the number of solar plants. Below is one possible way of doing this using df.query (which would work also if several rows had the same value of State). otherwise you could reindex the dataframe with the State Column (df2 = df.set_index('State')) and use loc : df2.loc['California']. Hope this helps!

@app.callback(
    dash.dependencies.Output('dd-output-container', 'children'),
    [dash.dependencies.Input('my-dropdown', 'value')])
def update_output(value):
    number_of_plants = int(df.query("State == '%s'"%value)['Number of Solar Plants'])
    return 'You have selected "{}" which has {} solar plants'.format(value, number_of_plants)
2 Likes

Many thanks Emmanuelle. This works. Appreciate it. Guess iā€™d revise my Pandas knowledge.

-D