如何修复Python美国航空航班数据Dash看板代码的缩进错误
修复方案
你遇到的缩进报错是多个语法错误共同导致的,所有问题点和修复后的完整代码如下:
核心错误点
compute_data_choice_1函数定义末尾缺少冒号,且整个函数体未缩进compute_data_choice_2函数定义后整个函数体未缩进get_graph回调函数、函数内的if/else代码块全部未正确缩进- 特殊变量拼写错误:
name应为__name__、'main'应为'__main__' - 装饰器
@app.callback和对应的函数定义之间不能有空行 - 初始化Dash应用时的参数应为
__name__而非name
修复后完整代码
# 导入所需库 import pandas as pd import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output, State import plotly.graph_objects as go import plotly.express as px from dash import no_update # 创建Dash应用 app = dash.Dash(__name__) # 清空布局,回调执行前不显示异常 app.config.suppress_callback_exceptions = True # 读取航空公司数据集到pandas dataframe airline_data = pd.read_csv( 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/airline_data.csv', encoding = "ISO-8859-1", dtype={'Div1Airport': str, 'Div1TailNum': str, 'Div2Airport': str, 'Div2TailNum': str} ) # 年份列表 year_list = [i for i in range(2005, 2021, 1)] """ 计算年度航空公司绩效报告所需的图表数据 接收筛选后的dataframe作为输入,返回5个分组后的dataframe用于绘图 参数: df: 筛选后的dataframe 返回: 绘图所需的dataframe """ def compute_data_choice_1(df): # 取消航班分类统计 bar_data = df.groupby(['Month','CancellationCode'])['Flights'].sum().reset_index() # 各航司平均飞行时长 line_data = df.groupby(['Month','Reporting_Airline'])['AirTime'].mean().reset_index() # 改道降落航班 div_data = df[df['DivAirportLandings'] != 0.0] # 出发州航班数量统计 map_data = df.groupby(['OriginState'])['Flights'].sum().reset_index() # 目的州航班数量统计 tree_data = df.groupby(['DestState', 'Reporting_Airline'])['Flights'].sum().reset_index() return bar_data, line_data, div_data, map_data, tree_data """ 计算年度航空公司延误报告所需的图表数据 接收航空公司数据和选中年份作为输入,返回各类延误的平均数据用于绘图 参数: df: 输入的航空公司数据 返回: 承运人延误、天气延误、NAS延误、安保延误、晚到飞机延误的平均dataframe """ def compute_data_choice_2(df): # 计算各类延误平均值 avg_car = df.groupby(['Month','Reporting_Airline'])['CarrierDelay'].mean().reset_index() avg_weather = df.groupby(['Month','Reporting_Airline'])['WeatherDelay'].mean().reset_index() avg_NAS = df.groupby(['Month','Reporting_Airline'])['NASDelay'].mean().reset_index() avg_sec = df.groupby(['Month','Reporting_Airline'])['SecurityDelay'].mean().reset_index() avg_late = df.groupby(['Month','Reporting_Airline'])['LateAircraftDelay'].mean().reset_index() return avg_car, avg_weather, avg_NAS, avg_sec, avg_late # 应用布局 app.layout = html.Div(children=[ # 看板标题 html.H2('美国国内航班运营绩效',style={'textAlign':'center','color':'#503d36','font-size':25}), # 下拉选择区域 html.Div([ html.Div([ html.Div( [ html.H2('报告类型:', style={'margin-right': '2em'}), ] ), # 报告类型下拉框 dcc.Dropdown(id='input-type', options=[{'label': '年度航司绩效报告', 'value':'OPT1'},{'label':'年度航司延误报告','value':'OPT2'}], placeholder="请选择报告类型", style={'width':'80%', 'padding':'3px', 'font-size': '20px', 'text-align-last' : 'center'}), ], style={'display':'flex'}), html.Div([ html.Div( [ html.H2('选择年份:', style={'margin-right': '2em'}) ] ), # 年份下拉框 dcc.Dropdown(id='input-year', options=[{'label': i, 'value': i} for i in year_list], placeholder="请选择年份", style={'width':'80%', 'padding':'3px', 'font-size': '20px', 'text-align-last' : 'center'}), ], style={'display': 'flex'}), ]), # 图表渲染区域 html.Div([ ], id='plot1'), html.Div([ html.Div([ ], id='plot2'), html.Div([ ], id='plot3') ], style={'display': 'flex'}), html.Div([ html.Div([ ], id='plot4'), html.Div([ ], id='plot5') ], style={'display': 'flex'}) ]) # 回调函数定义 @app.callback( [Output(component_id='plot1', component_property='children'), Output(component_id='plot2', component_property='children'), Output(component_id='plot3', component_property='children'), Output(component_id='plot4', component_property='children'), Output(component_id='plot5', component_property='children')], [Input(component_id='input-type', component_property='value'), Input(component_id='input-year', component_property='value')], [State("plot1", 'children'), State("plot2", "children"), State("plot3", "children"), State("plot4", "children"), State("plot5", "children") ]) def get_graph(chart, year, children1, children2, c3, c4, c5): # 筛选对应年份数据 df = airline_data[airline_data['Year']==int(year)] if chart == 'OPT1': # 计算绩效报告所需数据 bar_data, line_data, div_data, map_data,tree_data = compute_data_choice_1(df) # 不同取消原因的月度航班数量柱状图 bar_fig = px.bar(bar_data, x='Month', y='Flights', color='CancellationCode', title='月度航班取消情况') # 各航司月度平均飞行时长折线图 line_fig = px.line(line_data, x='Month', y='AirTime', color='Reporting_Airline', title='各航司月度平均飞行时长(分钟)') # 各航司改道降落航班占比饼图 pie_fig = px.pie(div_data, values='Flights', names='Reporting_Airline', title='各航司改道降落航班占比') # 各州出发航班数量热力图 map_fig = px.choropleth(map_data, locations='OriginState', color='Flights', hover_data=['OriginState', 'Flights'], locationmode = 'USA-states', color_continuous_scale='GnBu', range_color=[0, map_data['Flights'].max()]) map_fig.update_layout( title_text = '各州出发航班数量', geo_scope='usa') # 各目的州对应航司航班数量树形图 tree_fig = px.treemap(tree_data,path=['DestState', 'Reporting_Airline'],values='Flights',color='Flights',color_continuous_scale='RdBu',title='各航司飞往目的州航班数量') # 返回图表组件 return [dcc.Graph(figure=tree_fig), dcc.Graph(figure=pie_fig), dcc.Graph(figure=map_fig), dcc.Graph(figure=bar_fig), dcc.Graph(figure=line_fig) ] else: # 计算延误报告所需数据 avg_car, avg_weather, avg_NAS, avg_sec, avg_late = compute_data_choice_2(df) # 各类延误折线图 carrier_fig = px.line(avg_car, x='Month', y='CarrierDelay', color='Reporting_Airline', title='各航司平均承运人延误时长(分钟)') weather_fig = px.line(avg_weather, x='Month', y='WeatherDelay', color='Reporting_Airline', title='各航司平均天气延误时长(分钟)') nas_fig = px.line(avg_NAS, x='Month', y='NASDelay', color='Reporting_Airline', title='各航司平均NAS延误时长(分钟)') sec_fig = px.line(avg_sec, x='Month', y='SecurityDelay', color='Reporting_Airline', title='各航司平均安保延误时长(分钟)') late_fig = px.line(avg_late, x='Month', y='LateAircraftDelay', color='Reporting_Airline', title='各航司平均晚到飞机延误时长(分钟)') return[dcc.Graph(figure=carrier_fig), dcc.Graph(figure=weather_fig), dcc.Graph(figure=nas_fig), dcc.Graph(figure=sec_fig), dcc.Graph(figure=late_fig)] if __name__ == '__main__': app.run_server()
内容的提问来源于stack exchange,提问作者Ratnesh Pathak
相关产品推荐
相关产品推荐

