如何解决我的Dash应用程序的DataTable函数中的此错误

如何解决我的Dash应用程序的DataTable函数中的此错误

本文介绍了“期望一个数组.提供了类型“对象".如何解决我的Dash应用程序的DataTable函数中的此错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看我的代码并滚动到我的 statsTable(symbols)函数,这就是我的错误出现的地方.

please look at my code and scroll to my statsTable(symbols) function, that is where my error comes up.

import dash
import dash_table as dt
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objs as go
from dash.exceptions import PreventUpdate

import pandas as pd

from connect import *
from dash_tables import *


stock_ids = execute_query(conn, "SELECT DISTINCT id FROM security_price;")
stock_ids = [i[0] for i in stock_ids]
options = [{'label': i, 'value': i} for i in stock_ids]

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUX],  meta_tags=[
        {"name": "viewport", "content": "width=device-width, initial-scale=1"}])
body = html.Div(
    [dbc.Jumbotron(
    [
        dbc.Container(
    [
        html.H1("SP500", className="display-4"),
        html.P(
            "Compare equities in the SP500 "
            "before you buy.",
            className="lead",
        ),
        html.P(
            "Enter the symbols that interest you "
            "and view how they compare",

        ),

    ],
        fluid=True,
        )

    ],
    fluid=True,
)
    , dbc.Row(dbc.Container(dcc.Dropdown(id="dynamic-dropdown", options=options, multi=True, placeholder="Select a Symbol", style={'margin-left': '20px', 'margin-right':'45px'}),fluid=True))

    , dbc.Row(dbc.Col(html.Div(children = [dcc.Graph(id='output-graph', config={'displayModeBar': False}, animate=True)], style={'padding': 10})))



    , dbc.Row([
           (html.Div(dbc.Container(dt.DataTable(id='table_stats', style_table={'margin-left': '20px', 'margin-right':'45px'}))))], justify="center")

            # lg=9, md=6, xs=4, style={'margin-left': '5px','padding': 10})
             #dbc.Col(html.Div(dbc.Alert("One of three columns", color="primary")), lg=3, md=4, xs=12, style={'padding' : 10})
            # # , dbc.Col(html.Div(dbc.Alert("One of three columns", color="primary")), lg=3, md=4, xs=12,style={'margin-right': '5px','padding': 10})
            # ], justify="center")

    , dbc.Row(dbc.Col(html.Div(dbc.Alert("This is one column", color="primary", style={'margin-top' : '25px' ,'margin-bot' : '25px'}))),style={'margin-left' : '25px' ,'margin-right' : '25px'}, justify="center")
        ])






app.layout = html.Div([body])




@app.callback(
dash.dependencies.Output('table_stats', 'data'),
[dash.dependencies.Input('dynamic-dropdown', 'value')])



def statsTable(symbols):
    print(symbols)
    if symbols == None:
        raise PreventUpdate

    placeholders = ", ".join(['%s' for _ in symbols])

    # PREPARED STATEMENT WITH PARAM PLACEHOLDERS
    sql = f"""SELECT id, companyname, marketcap
                     , to_char(100.0*week52change,'999D99%%'), week52high, week52low
                     , to_char(dividend_yield * 100, '99D99%%'), next_earnings_date
                     , pe_ratio, ROUND(beta,2)
              FROM security_stats
              WHERE security_stats.id IN ({placeholders})
           """

    print(sql)

    df = postgresql_to_dataframe_v1(conn, sql, symbols, stats_col)
    columns = df.columns
    data = df.to_dict('rows')


    table = dt.DataTable(data=data, columns=columns)
    print(table)

    return table




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

这是 print(table),为您提供我正在传递的内容的示例:

This is print(table) to give you an example of what I'm passing:

DataTable(columns=Index(['Symbol', 'Company', 'Market Cap', '1yr-Change', '52-Week High',
       '52-Week Low', 'Dividend Yield', 'Next Earnings Report', 'PE-Ratio',
       'Beta'],
      dtype='object'), data=[{'Symbol': 'RSG', 'Company': 'Republic Services  Inc.', 'Market Cap': 31604176866, '1yr-Change': '  13.21%', '52-Week High': Decimal('102.58'), '52-Week Low': Decimal('65.78'), 'Dividend Yield': '  1.70%', 'Next Earnings Report': datetime.date(2020, 10, 25), 'PE-Ratio': Decimal('29.9'), 'Beta': Decimal('0.87')}])

这是 print(data),为您提供我正在传递的内容的示例:

This is print(data) to give you an example of what I'm passing:

[{'Symbol': 'RSG', 'Company': 'Republic Services  Inc.', 'Market Cap': 31604176866, '1yr-Change': '  13.21%', '52-Week High': Decimal('102.58'), '52-Week Low': Decimal('65.78'), 'Dividend Yield': '  1.70%', 'Next Earnings Report': datetime.date(2020, 10, 25), 'PE-Ratio': Decimal('29.9'), 'Beta': Decimal('0.87')}]

以下是Dash控制台中显示的错误:

Below is the error that appears in the Dash Console:

Invalid argument `data` passed into DataTable with ID "table_stats".
Expected an array.
Was supplied type `object`.

如何解决此错误?

推荐答案

您的回调具有以下输出:

Your callback has this output:

dash.dependencies.Output('table_stats','data'),

因此,您正在将返回的值提供给表的 data 属性.但这不是您的函数返回的结果.它返回一个数据表组件.

so you are supplying the returned value to the data prop of your table. But that's not what your function returns. It returns a datatable component.

您可能希望将输出更改为:

You probably will want to change your output to:


@app.callback(
[
    dash.dependencies.Output('table_stats', 'data'),
    dash.dependencies.Output('table_stats', 'columns'),
],
[dash.dependencies.Input('dynamic-dropdown', 'value')])

然后执行:

返回数据,列

在您的回调中.

这篇关于“期望一个数组.提供了类型“对象".如何解决我的Dash应用程序的DataTable函数中的此错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:00