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

Renaming the dataframe columns using dash dropdown selection

What i am trying to achieve?

Renaming the dataframe columns using dash dropdown selection (selectionlist for dropdown is the unique of column names from dataframe, values for the corresponding selectionlist is hardcoded which will be used to replace the column names)

  1. Read testdata to dataframe df (it has 4 fields)
  2. Create 4 dropdown based on the df.columns.unique
  3. Writing a call back function to pick selected values from each dropdown
  4. pass those 4 values from the corresponding dropdown to a function that renames the dataframe
  5. renamed dataframe is sent to generate table function
  6. Table is created in the html div

What is the challenge?

  1. dropdown selection value doesnot rename the appropriate column in the data frame. for example, when i select ‘YourAge’ for the dropdown label ‘Select Name’ it has to rename the first field in the dataframe to ‘Age’ instead it renames the second field ‘YourAge’ to ‘Age’
  2. Selection of dropdown should rename only the corresponding column in dataframe. For example when i select ‘YourName’ for the dropdown label ‘Select Name’ it renames field1 in dataframe to ‘Name’ and again if change the selection to ‘YourAge’ in the same dropdown it has to rename the field1 to ‘Age’ instead it renames the field2 ‘YourAge’ to ‘Age’
  3. After selecting 4 times from the dropdown, no changes occurs to the dataframe column.

Iam not sure what am i doing wrong, it would be big help if someone can help me correct the code to what i am trying to achieve.

Please see below for the code

import flask
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd

testdata = {‘YourName’:[‘Tom’, ‘Jack’, ‘Steve’, ‘Ricky’],‘YourAge’:[28,34,29,42]
,‘YourLocation’:[‘us’,‘uk’,‘ca’,‘eu’],‘YourSalary’:[280,340,290,420]}
df = pd.DataFrame(testdata)

def get_match_results(field1,field2,field3,field4):
‘’‘Returns match results for the selected prompts’’’

mvar = ''

if field1 == 'YourName':
  mvar = 'Name'
elif field1 == 'YourAge':
  mvar = 'Age'
elif field1 == 'YourLocation':
  mvar = 'Location'
else:
  mvar = 'Salary'

mvar1 = ''

if field2 == 'YourName':
  mvar1 = 'Name'
elif field2 == 'YourAge':
  mvar1 = 'Age'
elif field2 == 'YourLocation':
  mvar1 = 'Location'
else:
  mvar1 = 'Salary'

mvar2 = ''

if field3 == 'YourName':
  mvar2 = 'Name'
elif field3 == 'YourAge':
  mvar2 = 'Age'
elif field3 == 'YourLocation':
  mvar2 = 'Location'
else:
  mvar2 = 'Salary'

mvar3 = ''

if field4 == 'YourName':
  mvar3 = 'Name'
elif field4 == 'YourAge':
  mvar3 = 'Age'
elif field4 == 'YourLocation':
  mvar3 = 'Location'
else:
  mvar3 = 'Salary'

results_df = (df.rename(columns={
                     field1:mvar,
                     field2:mvar1,
                     field3:mvar2,
                     field4:mvar3
                     }
                    , inplace=True))
results_df = df

return results_df

def generate_table(dataframe, max_rows=10):
‘’‘Given dataframe, return template generated using Dash components
‘’’
return html.Table(
# Header
[html.Tr([html.Th(col) for col in dataframe.columns])] +

    # Body
    [html.Tr([
        html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
    ]) for i in range(min(len(dataframe), max_rows))]
)

server = flask.Flask(name)
app = dash.Dash(name, server=server)

app.css.append_css({
“external_url”: “https://codepen.io/chriddyp/pen/bWLwgP.css
})

column_options = []
for columns in df.columns.unique():
column_options.append({‘label’:str(columns),‘value’:columns})

column_options1 = []
for columns1 in df.columns.unique():
column_options1.append({‘label’:str(columns1),‘value’:columns1})

column_options2 = []
for columns2 in df.columns.unique():
column_options2.append({‘label’:str(columns2),‘value’:columns2})

column_options3 = []
for columns3 in df.columns.unique():
column_options3.append({‘label’:str(columns3),‘value’:columns3})

#########################

Dashboard Layout / View

#########################

app.layout = html.Div([
html.Div([
html.Div([

                    html.Div([
                                html.Div('Select Name', className='three columns'),
                                html.Div(dcc.Dropdown(id='column-picker1',
                                options=column_options#, #[{'label': k, 'value': k} for k in all_options.keys()], #column_options,
                                #value = df.columns[0]
                                )
                                ,className='nine columns')
                            ]),
                    html.Div([
                                html.Div('Select Age', className='three columns'),
                                html.Div(dcc.Dropdown(id='column-picker2',
                                options=column_options1
                                #, #[{'label': k, 'value': k} for k in all_options.keys()], #column_options1,
                                #value = df.columns[1]
                                )
                                ,className='nine columns')
                            ]),
                    html.Div([
                                html.Div('Select Location', className='three columns'),
                                html.Div(dcc.Dropdown(id='column-picker3',
                                options=column_options2 #, [{'label': k, 'value': k} for k in all_options.keys()], #column_options2,
                                #value = df.columns[2]
                                )
                                ,className='nine columns')
                            ]),
                    html.Div([
                                html.Div('Select Salary', className='three columns'),
                                html.Div(dcc.Dropdown(id='column-picker4',
                                options=column_options3#, #[{'label': k, 'value': k} for k in all_options.keys()], #column_options3,
                                #value = df.columns[3]
                                )
                                ,className='nine columns')
                            ]),
                ],className='six columns'),
# Empty
html.Div(className='six columns'),
], className='twleve columns'),

html.Div([

    # Match Results Table
    html.Div(

        html.Table(id='table-results'),

        className='six columns'
    )
    ])

])

@app.callback(Output(‘table-results’, ‘children’),
[
Input(‘column-picker1’, ‘value’),
Input(‘column-picker2’, ‘value’),
Input(‘column-picker3’, ‘value’),
Input(‘column-picker4’, ‘value’)
]
)
def update_datatable(field1,field2,field3,field4):
results_df = get_match_results(field1,field2,field3,field4)
#return df.to_html()
return generate_table(results_df) #generate_table(results_df, max_rows=50) #generate_table(df, max_rows=50)

start Flask server

if name == ‘main’:
app.run_server(
debug=True,
host=‘127.0.0.1’,
port=5000
)