Python全栈开发-第3章 时间序列分析(Prophet)
第一篇 · 数据分析与可视化🔮 第3章 时间序列分析(Prophet)预测未来—从趋势分析到智能预测3.1 时间序列基础与时间做朋友—理解日期数据和时序操作时间序列数据就是按时间顺序记录的数据—每天的股价、每月的销售额。处理时序数据要过三关:日期关:字符串→datetime对象索引关:日期设为索引,解锁时序功能重采样关:日/周/月/年自由转换importpandasaspdimportnumpyasnpfromdatetimeimportdatetime dt=datetime(2024,3,15,14,30)print(f'datetime:{dt}')print(f'年:{dt.year}月:{dt.month}日:{dt.day}')dates=pd.date_range('2024-01-01',periods=90,freq='D')print(f'\n日期范围:{dates[0]}~{dates[-1]}, 共{len(dates)}天')np.random.seed(42)sales=500+np.linspace(0,200,90)+50*np.sin(np.linspace(0,4*np.pi,90))sales+=np.random.normal(0,30,90)df=pd.DataFrame({'日期':dates,'销售额':sales.round(0).astype(int)})df.set_index('日期',inplace=True)print('\n=== 时间索引 ===')print(df.head())print(f'\n3月数据共{len(df["2024-03"])}天')print(df['2024-03'].head())print('\n=== 按周汇总 ===')print(df.resample('W').sum().head())print('\n=== 按月汇总 ===')print(df.resample('ME').sum())importpandasaspd,numpyasnp dates=pd.date_range('2024-01-01',periods=365,freq='D')np.random.seed(42)trend=np.linspace(1000,1500,365)seasonal=200*np.sin(np.linspace(0,2*np.pi*4,365))weekly=50*np.sin(np.linspace(0,2*np.pi*52,365))noise=np.random.normal(0,50,365)df=pd.DataFrame({'日期':dates,'销售额':(trend+seasonal+weekly+noise).round(0).astype(int)})df.set_index('日期',inplace=True)df['7日均线']=df['销售额'].rolling(window=7).mean()df['30日均线']=df['销售额'].rolling(window=30).mean()print('=== 滑动平均 ===')print(df[['销售额','7日均线','30日均线']].head(10))df['日环比']=df['销售额'].pct_change()*100print('\n=== 变化率 ===')print(df[['销售额','日环比']].dropna().head(10))💡 技巧resample频率代码:'D'天'W'周'ME'月末'QE'季末'YE'年末'h'小时'min'分钟⚠️ 注意️时区问题:Pandas默认创建无时区的datetime。需要时区用tz_localize('Asia/Shanghai')设置,tz_convert('UTC')转换。🔑 核心要点核心知识点:pd.to_datetime():字符串转日期pd.date_range():生成日期序列df.set_index('日期'):时间索引df.resample('W').sum():重采样df.rolling(7).mean():滑动平均df.pct_change():环比变化率🧪 随堂测验想要计算“每7天平均销售额”来平滑波动,应该用?A. df.resample(‘7D’).mean()B. df.rolling(window=7).mean()C. df.groupby(7).mean()D. A和B都可以,但含义不同答案解析:A和B都能得到7天平均值,但含义不同:resample(‘7D’)按7天分组求均值(行数变少);rolling(7)是滑动窗口(行数不变,产生平滑曲线)。要看“每周汇总”用resample,要“平滑曲线”用rolling。3.2 Prophet入门Facebook出品的预测神器—零门槛做预测传统时间序列预测(ARIMA等)需要深厚统计学功底。Prophet是Facebook开源的预测工具,设计目标是让非专家也能做出靠谱的预测。它擅长处理:带趋势的数据带季节性的数据(日/周/年周期)有节假日效应的数据有缺失值的数据# pip install prophetfromprophetimportProphetimportpandasaspd,numpyasnp np.random.seed(42)dates=pd.date_range('2022-01-01','2024-12-31',freq='D')n=len(dates)trend=np.linspace(500,800,n)yearly=100*np.sin(np.linspace(0,2*np.pi*3,n))noise=np.random.normal(0,30,n)df=pd.DataFrame({'ds':dates,'y':(trend+yearly+noise).round(0).astype(int)})print('=== Prophet数据格式 ===')print(df.head())print(f'数据量:{len(df)}天')