-1

在要求维度级别向下钻取之后,我试图在两个指标之间创建散点图。但是,我收到错误消息:KeyError: u'brand'(其中一个列名)。我是 Dash 新手,无法调试错误,因为列名没有任何问题。以下是代码:

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import sqlalchemy as sq
import numpy as np
from datetime import datetime

engine_prd = sq.create_engine(“connection url”)

df=pd.read_sql(“SELECT t1.date,
t1.article_type as article_type,
t1.product_gender as product_gender,
t1.brand as brand,
t1.master_category as master_category,
t1.business_unit as business_unit,
SUM(t1.revenue) as revenue,
SUM(t1.sold_quantity) as units_sold,
SUM(t1.total_discount) / NULLIF( SUM(t1.total_mrp),0) AS discount_perc,
SUM(t1.approved_po_quantity) - SUM(t1.po_inwarded_quantity) AS pending_invard_quantity,
SUM(t1.revenue) / NULLIF(SUM(t1.list_count), 0) AS rpi,
SUM(t1.list_count),
100 *ratio_to_report(SUM(t1.list_count)) OVER (PARTITION BY t1.DATE) AS lc_share
FROM fact_category_over_view_metrics t1 
WHERE t1.DATE> 20180101 and is_live_style=1
GROUP BY 
t1.DATE,t1.article_type,t1.product_gender,t1.brand,t1.master_category,
t1.business_unit;”,engine_prd)

df[[‘date_format’]] = df[[‘date’]].applymap(str).applymap(lambda s: “{}/{}/{}”.format(s[4:6],s[6:], s[0:4]))
df[[‘year_month’]]=df[[‘date’]].applymap(str).applymap(lambda s: “{}-{}”.format(s[0:4],s[4:6]))
df[‘year_month’]=df[‘year_month’].astype(str)

year_month=df[‘year_month’].unique()

available_indicators = np.array([‘revenue’,‘units_sold’,‘discount_perc’,‘pending_invard_quantity’,‘rpi’,‘lc_share’])
dimension_level=np.array([‘brand’,‘product_gender’,‘article_type’,‘master_category’,‘business_unit’])
#available_indicators=list(df)

app=dash.Dash()

app.layout = html.Div([
html.Div([

   html.Div([
          dcc.Dropdown(
                 id='dimension-level',
                 options=[{'label': i, 'value': i} for i in dimension_level],
                 value='brand'
          )]),

   html.Div([
        dcc.Dropdown(
            id='crossfilter-xaxis-column',
            options=[{'label': i, 'value': i} for i in available_indicators],
            value='revenue'
        ),
        dcc.RadioItems(
            id='crossfilter-xaxis-type',
            options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
            value='Linear',
            labelStyle={'display': 'inline-block'}
        )
    ],
    style={'width': '48%', 'display': 'inline-block'}),

    html.Div([
        dcc.Dropdown(
            id='crossfilter-yaxis-column',
            options=[{'label': i, 'value': i} for i in available_indicators],
            value='units_sold'
        ),
        dcc.RadioItems(
            id='crossfilter-yaxis-type',
            options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
            value='Linear',
            labelStyle={'display': 'inline-block'}
        )
    ], style={'width': '48%', 'float': 'right', 'display': 'inline-block'})
]),


   dcc.Graph(
          id='crossfilter-indicator-scatter'),

   dcc.Slider(
   id='crossfilter-year-month--slider',
   min=0,
   max=len(df['year_month'].unique()),
   value=0,
   step=None,
   marks={i : str(yearm) for i, yearm in enumerate(df['year_month'].unique())} # enumerate the dates
   )
])

@app.callback(
dash.dependencies.Output(‘crossfilter-indicator-scatter’, ‘figure’),
[dash.dependencies.Input(‘dimension-level’, ‘value’),
dash.dependencies.Input(‘crossfilter-xaxis-column’, ‘value’),
dash.dependencies.Input(‘crossfilter-yaxis-column’, ‘value’),
dash.dependencies.Input(‘crossfilter-xaxis-type’, ‘value’),
dash.dependencies.Input(‘crossfilter-yaxis-type’, ‘value’),
dash.dependencies.Input(‘crossfilter-year-month–slider’, ‘value’)],
[dash.dependencies.State(‘crossfilter-year-month–slider’, ‘marks’)])

def update_graph(dimension_level_name,xaxis_column_name, yaxis_column_name,xaxis_type, yaxis_type, selected_year_month_key,marks):

   selected_year_month=marks[str(selected_year_month_key)]
   df_filtered = df[df['year_month'] == selected_year_month]
   dff=df_filtered.groupby([dimension_level_name]).sum()


   return {
    'data': [go.Scatter(
        x=dff[xaxis_column_name],
        y=dff[yaxis_column_name],
        text=dff[dimension_level_name],
        #customdata=dff['article_type'],
        mode='markers',
        marker={
            'size': 15,
            'opacity': 0.5,
            'line': {'width': 0.5, 'color': 'white'}
        }
    )],
    'layout': go.Layout(
        xaxis={
            'title': xaxis_column_name,
            'type': 'linear' if xaxis_type == 'Linear' else 'log'
        },
        yaxis={
            'title': yaxis_column_name,
            'type': 'linear' if yaxis_type == 'Linear' else 'log'
        },
        margin={'l': 40, 'b': 30, 't': 10, 'r': 0},
        height=450,
        hovermode='closest'
    )
}

如果名称 == 'main': app.run_server()

使用下拉列表中的输入值按 df 分组时发生错误。数据框的头部外观已链接到示例数据

4

1 回答 1

0

关键错误发生在“text=dff[dimension_level_name]”中。这是因为在按数据框分组时,as_index 未设置为 False。这将引发一个关键错误。通过将 dff=df_filtered.groupby([dimension_level_name]).sum() 替换为: dff=df_filtered.groupby([dimension_level_name].as_index=False).sum() 解决了这个问题

于 2018-03-06T09:22:52.200 回答