未为第二个图表绘图划线(Python)定义名称

2024-10-02 08:17:34 发布

您现在位置:Python中文网/ 问答频道 /正文

1。我解析上传的数据并返回df_con: 结果:正常

def parse_data(contents, filename):
    content_type, content_string = contents.split(',')
    global df_con
    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            # Assume that the user uploaded a CSV or TXT file
            df_con = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # Assume that the user uploaded an excel file
            df_con = pd.read_excel(io.BytesIO(decoded))
        elif 'txt' or 'tsv' in filename:
            # Assume that the user upl, delimiter = r'\s+'oaded an excel file
            df_con = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')), delimiter = r'\s+')
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    return df_con

2。然后创建回调并进行分散。 结果:图表正确,但存在(轻微)错误“分配前引用的局部变量'df_con”。

@app.callback(Output('graph3', 'figure'),
              [Input('upload-data', 'contents'),
                Input('upload-data', 'filename')])
def update_graph_upload(contents, filename):
    if contents:
        contents = contents[0]
        filename = filename[0]
        df_con = parse_data(contents, filename)
    fig2 = go.Figure(
        data=[
            go.Scatter(
                x=df_con['datetime'], 
                y=df_con['fact'], 
                mode='lines+markers')
            ],
        layout=go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"]
        ))
    return fig2

3。创建一个函数来分析上传的数据并返回dfcnb 结果:看起来不错。(处理其他脚本)

def bal_costs_df(df_con):

    con = pyodbc.connect(
        'Driver={SQL Server};'
        'Server=HTIC--DB1.RF.RES;'
        'Database=EKX;'
        'Trusted_Connection=yes;'
    )

    df_con['plan'] = df_con['fact'].shift(168)
    querystringnp = f"""
        SELECT [ELSPOTP_LT_DATE_ID],
                  [ELSPOTP_LT_TIME_ID],
                  [ELSPOTP_PRICE]
        FROM [ET_DWH].[dbo].[FactElspotPrices]
        WHERE ELSPOTP_PAREA_ID = 1
        ORDER BY ELSPOTP_LT_DATE_ID
    """
    cursor = con.cursor()
    df_np = pd.read_sql(querystringnp, con) 
    
    #Many other data manipulation and return....
            
    return dfcnb

4。尝试根据df_con和bal_costs_df函数创建另一个图表。 结果:未定义获取的错误名称“df_con”。

@app.callback(Output('graph4', 'figure'),
              [Input('upload-data', 'contents'),
                Input('upload-data', 'filename')])
def update_graph2(contents, filename):
    dfm = bal_costs_df(df_con)  <<<<<<<<<<<<ERROR: "name 'df_con' is not defined"
    fig3 = go.Figure(
        data=[
            go.Scatter(
                x=dfm['datetime'], 
                y=dfm['balcosts'], 
                mode='lines+markers')
            ],
        layout=go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"]
        ))
    return fig3

你知道为什么图3可以,但图4的df_con没有定义吗?也许输入是错误的? 我希望数据与dfcnb dataframe一样,并从中创建图表。 谢谢


Tags: godfreadinputdatareturndefcontents
1条回答
网友
1楼 · 发布于 2024-10-02 08:17:34

这里有一个问题。任何时候当此函数运行时,内容的值为falsy时,您都不会定义df_con。在初始化期间,当使用None输入值触发回调时,这种情况至少会发生一次

def update_graph_upload(contents, filename):
    if contents:
        contents = contents[0]
        filename = filename[0]
        df_con = parse_data(contents, filename)

考虑到您需要df_con,并且为此您需要contents,我认为最好是

if not contents:
    raise dash.exceptions.PreventUpdate
contents = contents[0]
filename = filename[0]
df_con = parse_data(contents, filename)

在最后一个示例中:

@app.callback(Output('graph4', 'figure'),
              [Input('upload-data', 'contents'),
                Input('upload-data', 'filename')])
def update_graph2(contents, filename):
    dfm = bal_costs_df(df_con)  <<<<<<<<<<<<ERROR: "name 'df_con' is not defined"

df_con未在此函数中定义。我不建议尝试将其作为一种全球战略。如果您想在回调之间传递数据,那么我建议使用^{} component

相关问题 更多 >

    热门问题