使用 Python Pandas 和 Scikit-learn 进行销售数据分析和线性回归拟合
使用 Python Pandas 和 Scikit-learn 进行销售数据分析和线性回归拟合
本文将使用 Python 的 Pandas 和 Scikit-learn 库来对销售数据进行分析,并利用线性回归模型进行拟合,最终绘制拟合图。
1. 数据准备
首先,我们需要准备两个 Excel 文件,分别存储 JD 商品的销售数据和广告数据。
import pandas as pd
import numpy as np
aa = r'JDdata.xls'
bb = r'JDcar.xls'
dfaa = pd.DataFrame(pd.read_excel(aa))
dfbb = pd.DataFrame(pd.read_excel(bb))
df1 = dfaa[['业务日期', '金额']]
df2 = dfbb[['投放日期', '支出']]
# 显示所有列和设置宽度
# pd.set_option('display.max_columns', None)
# pd.set_option('display.width', 1000)
# pd.set_option('display.unicode.ambiguous_as_wide', True)
# pd.set_option('display.unicode.east_asian_width', True)
print(df1)
print(df2)
# 筛选非空且金额非零的数据
df1 = df1[df1['业务日期'].notnull() & df1['金额'] != 0]
df2 = df2[df2['投放日期'].notnull() & df2['支出'] != 0]
# 将日期列转换为日期时间格式
df1['业务日期'] = pd.to_datetime(df1['业务日期'])
dfData = df1.set_index('业务日期', drop=True)
df2['投放日期'] = pd.to_datetime(df2['投放日期'])
dfCar = df2.set_index('投放日期', drop=True)
# 按月汇总数据
dfData_month = dfData.resample('M').sum().to_period('M')
dfCar_month = dfCar.resample('M').sum().to_period('M')
# 导出结果
resultfilel = r'resultl.xls'
resultfile2 = r'result2.xls'
dfData_month.to_excel(resultfilel)
dfCar_month.to_excel(resultfile2)
2. 线性回归拟合
接下来,我们将使用 Scikit-learn 库中的线性回归模型来拟合广告费用和销售收入之间的关系。
# 导库
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# 确定 X (广告费用) 和 y (销售收入)
X = dfCar_month['支出'].values.reshape(-1, 1)
y = dfData_month['金额'].values
# 拟合线性模型
model = LinearRegression()
model.fit(X, y)
# 绘制拟合图
plt.scatter(X, y)
plt.plot(X, model.predict(X), color='red', linewidth=2)
plt.xlabel('广告费用')
plt.ylabel('销售收入')
plt.title('线性拟合图')
plt.show()
3. 结果解释
通过绘制的拟合图,我们可以直观地观察到广告费用与销售收入之间的关系。红色线代表拟合的线性模型,散点代表实际数据。我们可以根据拟合结果来分析广告费用对销售收入的影响,并制定相应的营销策略。
总结
本文介绍了如何使用 Python 的 Pandas 和 Scikit-learn 库进行销售数据分析,并利用线性回归模型进行拟合,最终绘制拟合图。该方法可以帮助我们更深入地了解数据之间的关系,并为决策提供依据。
原文地址: https://www.cveoy.top/t/topic/ebWZ 著作权归作者所有。请勿转载和采集!