首页 > 解决方案 > 试图从 df 中获取一个值以用作指示轴中轴范围的值

问题描述

我一直在尝试组合一个 Plotly Dash 应用程序,它将拉动我们的客户当前时间和历史时间,当前时间表示为衡量已使用的数量与允许的数量,这因客户而异,因此我没有可以输入的设定值作为整体值。因此,值 = 花费的小时数,范围为 [0,允许的小时数]

我曾尝试使用 .iloc 和 .values,但都没有将整数单独选为要使用的自变量。然而,我也有一种感觉,我在用破折号把东西搞砸了,所以如果有人能帮我把它拧开,这样我就可以在星期五之前把它呈现出来,那就太好了。

编辑

@mozway,对此感到抱歉(另外,显然输入发送)。csv 看起来像这样:

    Client | Hours Spent | Hours Allowed | Last Updated
     XXXX  |     30.81   |          60   |  2021-09-07

等等。至于精确定位,它在指标图中给了我一个错误


    elif client != "All":
    dff = dfhours.query('Client == "{}"'.format(client))
    ha = dff.values[0][5]
        
    fig = go.Figure(go.Indicator(
        domain = {'x': [0, 1], 'y': [0, 1]},
        value = dff['Hours Spent'],
        mode = "gauge+number",
        gauge = {'axis': {'range':[None, ha]}}))
    
    ValueError: 
        Invalid value of type 'pandas.core.series.Series' received
    for the 'value' property of indicator
    Received value: 0    30.81
    Name: Hours Spent, dtype: float64
    
    The 'value' property is a number and may be specified as:
      - An int or float

它应该使用 Hours Spent 中的值作为量表的值,并将 Hours Allowed 作为量表的结束。

结束编辑


    

    app = dash.Dash(__name__)
    
        dfhours = pd.read_csv("hothours9-7.csv")
        dfhours['Last Updated'] = pd.to_datetime(dfhours['Last Updated'])
    dfclients = pd.read_csv("hotclients9-7.csv")
    clients = clientlist['Client'].unique()
    
    app.layout = html.Div(children=[
        html.H1(
            children='Hello!',
            style={
                'textAlign': 'center'
            }
        ),
        
        html.Br(),
        
        html.Div([
            html.Label('Clients'),
            dcc.Dropdown(
                id='clients-list',
                options=[{'label': i, 'value': i} for i in clients],
                value='All',
                style = {'width': "80%"}
            ),
            dcc.Dropdown(
                id='info-drop',
                options = [{'label': i, 'value': i} for i in ['Historical Hours', 'Current Hours']],
                value = 'Current Hours',
            )
        ]),
        html.Br(),
        
       dcc.Graph(id='info-graph')         
    ])
    
    
    #-------------------------------------------
    
    @app.callback( 
                Output('info-graph','figure'),
                [Input('clients-list','value'),
                 Input('info-drop','value')])
    def update_graph(client,info):    
        if info == "Current Hours":
            if client == "All":
                fig = px.bar(dfhours, x="Client", y="Hours Spent")
            
            elif client != "All":
                dff = dfhours.query('Client == "{}"'.format(client))
                ha = dff.values[0][5]
            
                fig = go.Figure(go.Indicator(
                    domain = {'x': [0, 1], 'y': [0, 1]},
                    value = dff['Hours Spent'],
                    mode = "gauge+number",
                    gauge = {'axis': {'range':[None, ha]}}))
        elif info == 'Historical Hours':
            if client == "All":
                dcc.Checklist(
                    options = [{"label": x, "value": x} for x in dfclients['Client']]),
                fig = px.line(dfclients,x="Last Updated",y="Hours Spent",color="Client")
            
            elif client != "All":
                dff = dfclients.query('Client == "{}"'.format(client)),
                
                fig = px.line(dff, x="Last Updated",y="Hours Spent")
        return fig
    
    
    
    if __name__=='__main__':
        app.run_server(debug=False)

标签: pythonpandasplotlyplotly-dash

解决方案


  • 模拟了你的数据...
  • 过滤数据框后的简单情况,reset_index()然后允许您始终将行作为索引 0 访问(假设每个客户端一行)
  • 使用了dash 1.0.0,因此htmldcc包没有被导入而是被引用
  • 您在回调中构建未在任何地方使用的清单...
from jupyter_dash import JupyterDash
import dash
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go

# app = dash.Dash(__name__)
app = JupyterDash(__name__)

# dfhours = pd.read_csv("hothours9-7.csv")
# dfhours['Last Updated'] = pd.to_datetime(dfhours['Last Updated'])
# dfclients = pd.read_csv("hotclients9-7.csv")
# simulate data...
h = np.random.uniform(10, 40, 4)
dfhours = pd.DataFrame(
    {
        "Client": list("ABCD"),
        "Hours Spent": h,
        "Hours Allowed": h * np.random.uniform(1.5, 2, 4),
    }
)
clientlist = pd.DataFrame({"Client": list("ABCD")})
clients = clientlist["Client"].unique()
dfclients = pd.DataFrame(
    {
        "Last Updated": pd.date_range("1-May-2021", periods=60),
        "Client": np.random.choice(list("ABCD"), 60),
        "Hours Spent": np.random.uniform(10, 40, 60),
    }
)

app.layout = dash.html.Div(
    children=[
        dash.html.H1(children="Hello!", style={"textAlign": "center"}),
        dash.html.Br(),
        dash.html.Div(
            [
                dash.html.Label("Clients"),
                dash.dcc.Dropdown(
                    id="clients-list",
                    options=[{"label": i, "value": i} for i in clients],
                    value="All",
                    style={"width": "80%"},
                ),
                dash.dcc.Dropdown(
                    id="info-drop",
                    options=[
                        {"label": i, "value": i}
                        for i in ["Historical Hours", "Current Hours"]
                    ],
                    value="Current Hours",
                ),
            ]
        ),
        dash.html.Br(),
        dash.dcc.Graph(id="info-graph"),
    ]
)


# -------------------------------------------


@app.callback(
    Output("info-graph", "figure"),
    [Input("clients-list", "value"), Input("info-drop", "value")],
)
def update_graph(client, info):
    if info == "Current Hours":
        if client == "All":
            fig = px.bar(dfhours, x="Client", y="Hours Spent")

        elif client != "All":
            dff = dfhours.loc[dfhours["Client"].eq(client)].reset_index(drop=True)

            fig = go.Figure(
                go.Indicator(
                    domain={"x": [0, 1], "y": [0, 1]},
                    value=dff.loc[0, "Hours Spent"],
                    mode="gauge+number",
                    gauge={"axis": {"range": [0, dff.loc[0, "Hours Allowed"]]}},
                )
            )
    elif info == "Historical Hours":
        if client == "All":
            # this is spurious !!!
            dash.dcc.Checklist(
                options=[{"label": x, "value": x} for x in dfclients["Client"]]
            ),
            fig = px.line(dfclients, x="Last Updated", y="Hours Spent", color="Client")

        elif client != "All":
            dff = dfclients.query('Client == "{}"'.format(client))
            fig = px.line(dff, x="Last Updated", y="Hours Spent")
    return fig


if __name__ == "__main__":
    #     app.run_server(debug=False)
    app.run_server(mode="inline")

推荐阅读