用Python和Gradio构建现代仪表板|迈向数据科学
2025-06-04 22:33:11
要使用Gradio和CSV文件作为数据源来构建交互式销售性能仪表板,您可以按照以下步骤进行操作:###步骤1:设置您的环境确保已安装Python以及必要的库,例如“ Pandas”,“ Matplotlib”和“ Gradio”。您可以使用PIP安装所需的库:``bashPIP安装pandas matplotlib gradio openpyxl````````###步骤2:创建示例数据CSV文件如果您还没有示例数据文件,请生成一个使用合成销售数据的文件。这是如何在Python中创建此类文件的示例:``python导入大熊猫作为pd来自Faker Import Faker导入numpy作为NP从DateTime导入Timedelta,DateTime假= faker()#在特定年之间生成随机日期def Random_date(start_year = 2018,end_year = 2023):start = dateTime(start_year,1,1)end = dateTime(end_year,12,31)delta =结束 - 开始Random_days = np.random.randint(delta.days + 1)返回开始 + TIMEDELTA(days = andural_days)#生成合成数据num_records = 5000数据= {'order_date':[random_date()for _ in range(num_records)],'customer_id':[fake.unique.random_int(min = 1,max = 100),_范围(num_records)],'product_id':[fake.unique.random_int(min = 1,max = 50),_范围(num_records)],'类别':[fake.random_element(elements =('electronics','furniture','clotsing')for range(num_records)],],'数量':[np.random.randint(1,10)for _ in range(num_records)],'unit_price':[round(np.random.uliform(5.0,200.0),2)_在范围内(num_records)]}df = pd.dataframe(数据)df ['order_date'] = df ['order_date']。dt.date#保存到CSVdf.to_csv('sales_data.csv',index = false)````````###步骤3:加载数据并定义功能将CSV数据加载到PANDAS数据框架中,并定义用于过滤,计算指标,生成图等的功能。``python导入大熊猫作为pd从DateTime Import DateTime导入matplotlib.pyplot作为PLT导入Gradio作为GR导入tempfile导入numpy作为NP#从CSV文件加载数据df = pd.read_csv('sales_data.csv')def Random_date(start_year = 2018,end_year = 2023):start = dateTime(start_year,1,1)end = dateTime(end_year,12,31)delta =结束 - 开始Random_days = np.random.randint(delta.days + 1)返回(start + timedelta(days = randy_days))。date()def get_dashboard_stats(df,start_date,end_date,类别):filted_df = df [(df ['order_date']> = start_date)&(df ['order_date'] <= end_date)]如果类别!='所有类别':FILFERED_DF = FILFERED_DF [FILFERED_DF ['类别'] ==类别]total_revenue =(filtered_df ['Quantity'] * filtered_df ['unit_price'])。sum()total_orders = len(effled_df)avg_order_value = total_revenue / total_orders如果total_orders> 0 else 0 0top_category = df ['category']。value_counts()。idxmax()如果类别=='所有类别'返回total_revenue,total_orders,avg_order_value,top_categorydef create_matplotlib_figure(data,x_col,y_col,title,xlabel,ylabel,entientation ='v'):plt.figure(无花果=(10,6))如果data.empty:plt.text(0.5,0.5,'无数据可用',ha ='Center',va ='Center')别的:如果方向=='v':plt.bar(数据[x_col],数据[y_col])plt.xticks(旋转= 45,ha ='right')别的:plt.barh(数据[x_col],数据[y_col])plt.gca()。invert_yaxis()plt.title(标题)plt.xlabel(xlabel)plt.ylabel(Ylabel)plt.tight_layout()使用tempfile.MegedTemporaryFile(delete = false,suffix =“。png”)作为tmpfile:plt.savefig(tmpfile.name)plt.close()返回tmpfile.namedef update_dashboard(start_date,end_date,类别):total_revenue,total_orders,avg_order_value,top_category = get_dashboard_stats(df,start_date,end_date,end_date,类别)Revenue_data = df [(df ['order_date']> = start_date)&(df ['order_date'] <= end_date)]如果类别!='所有类别':Revenue_data = Revenue_data [Revenue_data ['cattory'] ==类别]Revenue_over_time_path = create_matplotlib_figure(Revenue_data.groupby('order_date')。sum()。reset_index(),'order_date','total_revenue',“随着时间的收入”,“日期”,“收入”)Revenue_by_category_path = create_matplotlib_figure(df [df ['category'] == top_category] .groupby('category')。sum()。reset_index(),'类别','total_revenue',“按类别收入”,“类别”,“收入”)top_products_data = df.groupby(['product_id'])。agg({{'unit_price':'mean','nature':'sum'})。reset_index()如果类别!='所有类别':top_products_data = top_products_data [top_products_data ['category'] ==类别]top_products_path = create_matplotlib_figure(TOP_PRODUCTS_DATA.SORT_VALUES(by ='total_revenue',上升= false).head(10),'product_id','total_revenue',“顶级产品”,“产品ID”,“收入”,方向='h')返回 (Revenue_over_time_path,Revenue_by_category_path,top_products_path,total_revenue,total_orders,avg_order_value,top_category)````````###步骤4:创建仪表板UI使用Gradio创建交互式仪表板。``pythondef create_dashboard():min_date = df ['order_date']。min()()max_date = df ['order_date']。max()default_start_date = min_date.strftime('%y-%m-%d')default_end_date = max_date.strftime('%y-%m-%d')使用Gr.Blocks(CSS =“”“”页脚{display:无!重要;}.tabs {border:none!重要;}.gr-plot {border:none!盒子阴影:无!重要;}“”)作为仪表板:Gr.markDown(“#销售性能仪表板”)#过滤行使用Gr.Row():start_date = gr.textbox(label =“ start date”,value = default_start_date)end_date = gr.textbox(label =“ end Date”,value = default_end_date)category_filter = gr.dropdown(选择= ['所有类别'] + df ['category']。unique()。tolist(),标签=“类别”,值='所有类别')#关键指标total_revenue = gr.number(label =“总收入”)total_orders = gr.number(label =“总订单”)avg_order_value = gr.number(label =“平均订单值”)top_category = gr.textbox(label =“ top centory”)#可视化Revenue_over_over_time_image = gr.image()Revenue_by_category_image = gr.image()top_products_image = gr.image()#数据表(图下方)data_table = gr.dataframe(Interactive = false)def update_dashboard_(start_date,end_date,类别):start_date = dateTime.strptime(start_date,'%y-%m-%d')end_date = dateTime.strptime(end_date,'%y-%m-%d')((Revenue_over_time_path,Revenue_by_category_path,top_products_path,total_revenue_value,total_orders_value,avg_order_value_value,top_category_value)= update_dashboard(start_date.date(),end_date.date(),类别)返回 (Revenue_over_time_path,Revenue_by_category_path,top_products_path,df [(df ['order_date']> = start_date)&(df ['order_date'] <= end_date)],total_revenue_value,total_orders_value,avg_order_value_value,top_category_value)#滤波器更改时,更新所有内容对于[start_date,end_date,category_filter]:f.change(fn = update_dashboard_,inputs = [start_date,end_date,category_filter],outputs = [Revenue_over_time_image,Revenue_by_category_image,top_products_image,data_table,total_revenue,total_orders,avg_order_value,top_category)))#初始加载dashboard.load(fn = update_dashboard_,输入= [start_date,end_date,category_filter],输出= [Revenue_over_time_image,Revenue_by_category_image,top_products_image,data_table,total_revenue,total_orders,avg_order_value,top_category],,fn_kwargs = {“ start_date”:default_start_date,“ end_date”:default_end_date,“ category”:“所有类别”})返回仪表板如果__name__ ==“ __ -main __”:仪表板= create_dashboard()dashboard.launch(share = false)````````###步骤5:运行仪表板将所有代码保存在python文件中(例如`gradio_test.py`)并运行:``bashpython gradio_test.py````````这将启动一个托管您的交互式销售性能仪表板的Web服务器。您可以与过滤器进行交互,查看指标和可视化现场。###关键组件的说明 - **数据加载**:将CSV文件加载到PANDAS DataFrame中。 - **过滤功能**:基于用户输入日期和类别的过滤数据。 - **可视化功能**:使用matplotlib创建图并将其保存为图像。 - ** gradio ui **:提供了一种简单的方法,可以通过文本框,下拉框和图像小部件与仪表板进行交互。### 结论这种方法使您可以使用Python和Gradio构建交互式销售性能仪表板。您可以通过添加更多功能或将其集成到较大的应用程序中来进一步自定义。例如,您可以添加用户身份验证,将其部署在Heroku之类的云服务上,或与其他数据源集成以进行实时分析。对于其他自定义或更复杂的用例,请考虑利用高级库,例如“简化”或使用Flask或Django等框架构建成熟的Web应用程序。愉快的编码!🚀