首页 > 解决方案 > Plotly Dash:单击“清除值”时出错

问题描述

我用 Plotly Dash 创建了条形图。一切正常,但是当我单击“清除值”时: 在此处输入图像描述

我收到下一条错误消息:

    KeyError: ('Quantity', 'declined')
    Traceback (most recent call last)
    File "C:\Users\iakubal\Anaconda3\envs\general_3_6\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
    File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
    File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
    File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
    File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
    During handling of the above exception, another exception occurred:
    File "pandas\_libs\index.pyx", line 701, in pandas._libs.index.BaseMultiIndexCodesEngine.get_loc
    File "C:\Users\iakubal\Anaconda3\envs\general_3_6\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
    File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
    File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
    File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
    File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
    During handling of the above exception, another exception occurred:
    File "pandas\_libs\index.pyx", line 704, in pandas._libs.index.BaseMultiIndexCodesEngine.get_log
    KeyError: ('Quantity', 'declined')
Traceback (most recent call last):
  File "C:\Users\iakubal\Anaconda3\envs\general_3_6\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'declined'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "pandas\_libs\index.pyx", line 701, in pandas._libs.index.BaseMultiIndexCodesEngine.get_loc
  File "C:\Users\iakubal\Anaconda3\envs\general_3_6\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item  
KeyError: 'declined'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "pandas\_libs\index.pyx", line 704, in pandas._libs.index.BaseMultiIndexCodesEngine.get_loc
KeyError: ('Quantity', 'declined')

此外,当我单击“清除值”时,它应该显示原始图,但它没有这样做。

我试图将一个数据框更改为另一个,但我仍然遇到同样的错误。它在寻找我,因为 Pandas 存在一些问题。这是可重现的代码片段(取自此处):

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

# Read in the data from Excel
df = pd.read_excel(
    "https://github.com/chris1610/pbpython/blob/master/data/salesfunnel.xlsx?raw=True"
)

# Get a list of all the avilable managers
mgr_options = df["Manager"].unique()

# Create the app
app = dash.Dash()

# Populate the layout with HTML and graph components
app.layout = html.Div([
    html.H2("Sales Funnel Report"),
    html.Div(
        [
            dcc.Dropdown(
                id="Manager",
                options=[{
                    'label': i,
                    'value': i
                } for i in mgr_options],
                value='All Managers'),
        ],
        style={'width': '25%',
               'display': 'inline-block'}),
    dcc.Graph(id='funnel-graph'),
])


# Add the callbacks to support the interactive componets
@app.callback(
    dash.dependencies.Output('funnel-graph', 'figure'),
    [dash.dependencies.Input('Manager', 'value')])
def update_graph(Manager):
    if Manager == "All Managers":
        df_plot = df.copy()
    else:
        df_plot = df[df['Manager'] == Manager]

    pv = pd.pivot_table(
        df_plot,
        index=['Name'],
        columns=["Status"],
        values=['Quantity'],
        aggfunc=sum,
        fill_value=0)

    trace1 = go.Bar(x=pv.index, y=pv[('Quantity', 'declined')], name='Declined')
    trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')
    trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')
    trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')

    return {
        'data': [trace1, trace2, trace3, trace4],
        'layout':
        go.Layout(
            title='Customer Order Status for {}'.format(Manager),
            barmode='stack')
    }


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

希望这个片段将有助于找到答案。

标签: pythonplotlyplotly-dash

解决方案


您可以在回调函数的顶部添加类似这样的内容:

if Manager is None:
    raise dash.exceptions.PreventUpdate

编辑:从更改到原始问题,我相信这会给你你正在寻找的行为:

    if Manager == "All Managers" or Manager is None:
        df_plot = df.copy()
    else:
        df_plot = df[df['Manager'] == Manager]

这对用户来说是一种棘手的行为,因为它本质上是隐藏了一个选项。最好包含此选项 (Manger == "All Managers")作为下拉选项之一,然后将下拉设置为 have clearable=False


推荐阅读