ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

共享单车数据分析:Python实现时间与气象因素可视化

共享单车数据分析:Python实现时间与气象因素可视化 1. 项目概述这个毕业设计项目聚焦于共享单车系统的数据分析与可视化通过对华盛顿地区2011-2012年的共享单车使用数据进行深入挖掘揭示了影响单车租借量的关键因素。作为一名数据分析师我认为这类项目不仅具有学术价值更能为实际运营决策提供数据支撑。项目采用了典型的数据分析流程从原始数据清洗开始到特征工程处理最后通过多种可视化手段呈现分析结果。整个过程使用了Python生态中的主流工具链包括Pandas进行数据处理Matplotlib和Seaborn进行基础可视化以及Pyecharts实现交互式图表。2. 数据准备与清洗2.1 原始数据特征解析原始数据集包含以下核心字段时间信息datetime精确到小时气象数据temp温度、atemp体感温度、humidity湿度、windspeed风速分类变量season季节、holiday节假日、workingday工作日、weather天气状况目标变量casual非注册用户租借量、registered注册用户租借量、count总租借量提示在实际项目中建议首先仔细阅读数据字典明确每个字段的业务含义和取值范围这对后续分析至关重要。2.2 数据清洗实战数据清洗是确保分析质量的关键步骤本项目主要进行了以下处理# 核心清洗代码示例 import pandas as pd from datetime import datetime # 读取原始数据 df pd.read_csv(bike_sharing.csv) # 处理分类变量 season_map {1:spring, 2:summer, 3:fall, 4:winter} weather_map {1:Good, 2:Normal, 3:Bad, 4:Very Bad} df[season] df[season].map(season_map) df[weather] df[weather].map(weather_map) # 时间特征工程 df[datetime] pd.to_datetime(df[datetime]) df[year] df[datetime].dt.year df[month] df[datetime].dt.month df[day] df[datetime].dt.day df[hour] df[datetime].dt.hour df[weekday] df[datetime].dt.weekday # 周一0周日6 # 检查缺失值 print(df.isnull().sum())清洗过程中发现几个关键点原始数据质量较好没有缺失值时间字段需要从字符串转换为datetime类型分类变量使用数字编码需要映射为可读标签通过dt访问器可以方便地提取各种时间维度特征2.3 特征相关性分析在深入可视化之前我们先通过统计方法了解变量间的关系import seaborn as sns import matplotlib.pyplot as plt # 计算相关系数矩阵 corr_matrix df[[temp,atemp,humidity,windspeed,count]].corr() # 绘制热力图 plt.figure(figsize(10,8)) sns.heatmap(corr_matrix, annotTrue, cmapcoolwarm, center0) plt.title(Feature Correlation Matrix) plt.show()分析结果显示temp和atemp与租借量(count)的相关性最高(约0.4)humidity呈现轻微负相关(-0.32)windspeed相关性最低(-0.1)3. 数据可视化与洞察3.1 时间维度分析年度趋势对比# 按年月聚合数据 monthly_trend df.groupby([year,month])[count].sum().unstack(level0) # 绘制对比折线图 plt.figure(figsize(12,6)) monthly_trend.plot(kindline, style--o, linewidth2, color[#1f77b4,#ff7f0e], figsize(12,6)) plt.title(Monthly Rental Trend: 2011 vs 2012) plt.xlabel(Month) plt.ylabel(Total Rentals) plt.grid(True, linestyle--, alpha0.7) plt.legend(titleYear) plt.show()关键发现2012年各月租借量均显著高于2011年平均增长约120%租借量呈现明显的季节性特征夏季6-8月达到峰值冬季11月-次年2月租借量明显下降小时模式分析# 按小时分析租借模式 hourly_pattern df.groupby([hour,workingday])[count].mean().unstack() plt.figure(figsize(14,6)) hourly_pattern.plot(kindline, style[-,--], linewidth2, color[#2ca02c,#d62728]) plt.title(Hourly Rental Pattern by Day Type) plt.xlabel(Hour of Day) plt.ylabel(Average Rentals) plt.xticks(range(24)) plt.grid(True, linestyle:, alpha0.5) plt.legend([Weekend/Holiday,Weekday], titleDay Type) plt.show()工作日与休息日的显著差异工作日呈现典型双峰模式早高峰(7-9点)和晚高峰(16-18点)休息日呈现单峰模式高峰出现在午后(12-16点)工作日早高峰的租借量明显高于休息日峰值3.2 气象因素影响温度与租借量关系# 温度分段分析 df[temp_bin] pd.cut(df[temp], bins10) temp_effect df.groupby(temp_bin)[count].mean() plt.figure(figsize(12,6)) temp_effect.plot(kindbar, color#17becf) plt.title(Rental Count by Temperature Range) plt.xlabel(Temperature Range (°C)) plt.ylabel(Average Rentals) plt.xticks(rotation45) plt.grid(True, axisy, linestyle--, alpha0.5) plt.show()温度影响的关键结论租借量在15-30°C区间最高低于5°C或高于35°C时租借量显著下降最适宜温度区间为20-25°C天气状况影响# 天气影响分析 weather_effect df.groupby(weather)[count].agg([mean,count]) fig, (ax1, ax2) plt.subplots(1, 2, figsize(16,6)) # 平均租借量 weather_effect[mean].plot(kindbar, axax1, color#9467bd) ax1.set_title(Average Rentals by Weather Condition) ax1.set_ylabel(Average Rentals) ax1.grid(True, axisy, linestyle--, alpha0.5) # 数据点数量 weather_effect[count].plot(kindbar, axax2, color#8c564b) ax2.set_title(Data Points Count by Weather Condition) ax2.set_ylabel(Number of Records) ax2.grid(True, axisy, linestyle--, alpha0.5) plt.tight_layout() plt.show()天气因素的影响天气越好租借量越高Good Normal BadVery Bad天气的记录很少仅占0.2%可能不具有统计意义恶劣天气下的租借量下降约30-50%3.3 用户类型差异注册用户 vs 非注册用户# 用户类型分析 user_type df.groupby(hour)[[registered,casual]].mean() plt.figure(figsize(14,6)) user_type.plot(kindline, linewidth2, color[#e377c2,#7f7f7f]) plt.title(Hourly Rental Pattern by User Type) plt.xlabel(Hour of Day) plt.ylabel(Average Rentals) plt.xticks(range(24)) plt.grid(True, linestyle:, alpha0.5) plt.legend([Registered Users,Casual Users]) plt.show()用户行为差异注册用户数量远高于非注册用户约3:1比例注册用户呈现明显的通勤特征早晚高峰突出非注册用户更多在日间使用10am-5pm工作日模式对比# 工作日与非工作日对比 workday_pattern df.groupby([workingday,hour])[[registered,casual]].mean() fig, (ax1, ax2) plt.subplots(1, 2, figsize(16,6), shareyTrue) # 工作日模式 workday_pattern.loc[1].plot(axax1, linewidth2, color[#e377c2,#7f7f7f]) ax1.set_title(Weekday Rental Pattern) ax1.set_xlabel(Hour of Day) ax1.set_ylabel(Average Rentals) ax1.grid(True, linestyle:, alpha0.5) # 非工作日模式 workday_pattern.loc[0].plot(axax2, linewidth2, color[#e377c2,#7f7f7f]) ax2.set_title(Weekend/Holiday Rental Pattern) ax2.set_xlabel(Hour of Day) ax2.grid(True, linestyle:, alpha0.5) plt.tight_layout() plt.show()工作日/休息日差异工作日注册用户主导早晚高峰明显休息日两种用户类型差异缩小非注册用户比例上升休息日下午时(12-16点)租借量高于工作日同时段4. 高级分析与模型构建4.1 特征重要性分析from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split # 准备特征和目标变量 features df[[season,holiday,workingday,weather, temp,atemp,humidity,windspeed, year,month,day,hour,weekday]] target df[count] # 转换分类变量 features pd.get_dummies(features, columns[season,weather]) # 拆分训练测试集 X_train, X_test, y_train, y_test train_test_split( features, target, test_size0.2, random_state42) # 训练随机森林模型 rf RandomForestRegressor(n_estimators100, random_state42) rf.fit(X_train, y_train) # 特征重要性可视化 importance pd.DataFrame({ feature: features.columns, importance: rf.feature_importances_ }).sort_values(importance, ascendingFalse) plt.figure(figsize(12,6)) sns.barplot(ximportance, yfeature, dataimportance.head(10)) plt.title(Top 10 Important Features for Rental Prediction) plt.xlabel(Importance Score) plt.ylabel(Feature) plt.show()特征重要性结果显示小时(hour)是最重要的预测因子温度相关特征(temp/atemp)次之天气状况和季节也有显著影响是否为工作日(workingday)比节假日(holiday)更重要4.2 预测模型构建from sklearn.metrics import mean_squared_error, r2_score from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.linear_model import Ridge # 创建建模管道 model make_pipeline( StandardScaler(), Ridge(alpha1.0) ) # 训练模型 model.fit(X_train, y_train) # 评估模型 y_pred model.predict(X_test) rmse np.sqrt(mean_squared_error(y_test, y_pred)) r2 r2_score(y_test, y_pred) print(fRMSE: {rmse:.2f}) print(fR2 Score: {r2:.2f}) # 实际 vs 预测可视化 plt.figure(figsize(10,6)) plt.scatter(y_test, y_pred, alpha0.3) plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], r--) plt.xlabel(Actual Rentals) plt.ylabel(Predicted Rentals) plt.title(Actual vs Predicted Rental Count) plt.grid(True, linestyle--, alpha0.5) plt.show()模型评估结果RMSE约为50考虑到租借量范围在0-1000之间表现尚可R²约为0.65说明模型能解释约65%的变异预测值与实际值的散点图显示模型对中低租借量预测较好高值预测偏保守5. 项目总结与建议5.1 主要研究发现时间模式租借量呈现明显的季节性和小时模式工作日早晚高峰需求集中休息日午后需求较高2012年较2011年有显著增长约120%气象影响温度在15-30°C区间租借量最高晴天租借量比恶劣天气高30-50%风速超过25km/h时租借量显著下降用户差异注册用户占主导约75%注册用户呈现规律的通勤模式非注册用户更多在日间和休息日使用5.2 运营建议基于分析结果对共享单车运营提出以下建议车辆调度优化工作日早晚高峰前增加商业区和办公区车辆投放休息日增加公园和景点周边的车辆供应冬季适当减少总投放量夏季增加投放定价策略恶劣天气可提供优惠鼓励使用非高峰时段针对非注册用户推出促销活动考虑温度分段定价策略用户增长加强通勤时段的注册用户推广针对非注册用户设计周末专属套餐在温度适宜的季节加大营销力度5.3 项目扩展方向数据层面引入更多年份数据观察长期趋势整合地理信息进行空间分析加入促销活动等运营数据技术层面尝试更复杂的预测模型如XGBoost、LSTM开发实时预测系统构建动态可视化仪表板业务层面研究用户留存率与气象因素的关系分析不同站点的供需特征评估定价弹性对需求的影响
返回列表