I am trying to reduce the amount of IF statements I have in various callbacks linking dropdowns to graphs as it is slowing the app down. I have provided a much simplified version of what one callback looks like:
The function is reading different rows of a database and adding them if they are selected within the dropdown. I’ve been trying to simplify the process using a for loop but I can’t seem to get it - whatever I seem to try doesn’t link the selection in the dropdown to the value displayed on the graph. Is there a way that I can prevent just having endless IF statements?
Apologies I am new to both Python programming and dash.
This looks almost like it’s more about how to use Pandas efficiently rather than Dash. It depends a bit on what your data looks like, but probably you want to have your selectors as columns and then slice the dataframe, so if you had columns called car_type
and fuel_type
or similar you could do something like the following:
cost = data.loc[(data.car_type == selector1) & (data.fuel_type == selector2), 'cost'].sum()
Thank you for the reply - you’re right it is more of a panda’s issue I am struggling with. My data is laid out slightly differently to having the selectors as the columns. As an example something like this:
Essentially the choice of car is the base value and then any further selections would be an addition/subtraction or multiplication to this value.
In which case you could maybe try something like this?
row_mask = data.Option.isin([selector1, selector2, ...])
cost = data.loc[row_mask, 'cost'].sum()
i.e. get all the rows with a selected option, then sum the cost column.
1 Like
Exactly what I’ve been trying to achieve, thank you!!
1 Like