模拟生成了一家保险公司过去10年(2008-2017)的10款产品的销售数据,并使用线性回归模型预测了这些产品未来5年(2018-2022)的销售情况。最终,它将所有15年(过去10年加未来5年)的销售数据和预测保存到一个Excel文件中,并在该Excel文件中创建了每个产品每年销售情况的柱状图。
import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression import openpyxl from openpyxl.chart import BarChart, Reference # 设置随机种子以便复现 np.random.seed(0) # 生成年份和产品信息 years = np.arange(2008, 2018) products = [f'Product_{i}' for i in range(1, 11)] # 生成10年的销售数据 xpanx.com data = [] for year in years: for product in products: sales = np.random.randint(1000, 5000) data.append([year, product, sales]) df = pd.DataFrame(data, columns=['Year', 'Product', 'Sales']) # 生成未来5年的销售预测 predictions = [] for product in products: product_data = df[df['Product'] == product] X = product_data[['Year']] y = product_data['Sales'] model = LinearRegression() model.fit(X, y) future_years = np.arange(2018, 2023) future_sales = model.predict(future_years.reshape(-1, 1)) for year, sales in zip(future_years, future_sales): predictions.append([year, product, sales]) df_pred = pd.DataFrame(predictions, columns=['Year', 'Product', 'Sales']) # 合并实际和预测数据 df_all = pd.concat([df, df_pred], ignore_index=True) # 保存到Excel文件 excel_path = 'Insurance_Company_Sales_Data.xlsx' with pd.ExcelWriter(excel_path) as writer: df_all.to_excel(writer, sheet_name='All_Sales', index=False) # 用openpyxl添加柱状图 xpanx.com wb = openpyxl.load_workbook(excel_path) ws = wb['All_Sales'] for idx, product in enumerate(products, 1): chart = BarChart() chart.title = f"Sales Data for {product}" chart.x_axis.title = "Year" chart.y_axis.title = "Sales" min_row = 2 + (idx - 1) * 10 max_row = min_row + 9 data = Reference(ws, min_col=3, min_row=min_row, max_row=max_row, max_col=3) chart.add_data(data, titles_from_data=False) cats = Reference(ws, min_col=1, min_row=min_row, max_row=max_row) chart.set_categories(cats) ws.add_chart(chart, f"E{min_row}") wb.save(excel_path)
知识点解释
- Python基础语法:脚本使用Python编程语言。Python是一个高级、解释型、交互式和面向对象的脚本语言。
- NumPy库:用于数值计算,尤其是对于大型数组和矩阵的操作。在这个脚本中,我们使用NumPy生成随机的销售数据和年份数组。
np.random.seed(0) np.random.randint(1000, 5000)
3、Pandas库:数据分析和操作库。在这个脚本中,Pandas用于创建和操作数据框(DataFrame),这是一个二维标签化数据结构。
pd.DataFrame(data, columns=['Year', 'Product', 'Sales'])
4、scikit-learn库:机器学习库,提供了多种机器学习算法的实现。在这里,我们使用了该库的LinearRegression
模型来预测未来销售。
model = LinearRegression() model.fit(X, y)
5、openpyxl库:用于读写Excel(.xlsx)文件。在这里,该库用于在Excel工作簿中添加柱状图。
chart = BarChart() ws.add_chart(chart, f"E{min_row}")
Excel操作:该脚本不仅保存数据到Excel文件中,还使用openpyxl库在Excel工作簿中动态创建图表。
线性回归:这是一个监督学习算法,用于找出输入和输出之间的线性关系。在这个脚本中,年份是输入(或特征),销售额是输出(或目标变量)。
数据可视化:通过在Excel中创建柱状图,该脚本实现了基本的数据可视化,使得销售数据更易于理解和解释。
文件I/O:脚本使用Pandas和openpyxl库进行文件输入/输出操作,将数据和图表保存到Excel文件中。
https://xpanx.com/
评论