项目背景:
本实训以自行车租赁统计数据为例,使用Pandas中的时间序列分析方法,探究自行车租赁数据随时间及天气变化的分布情况。采用的数据可在Kaggle网站(Bike Sharing Demand Stella | Kaggle)下载
任务步骤:
1.导入模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
2.获取数据,并显示前五行
bike=pd.read_csv("bikesharingdata.csv")
bike.head(5)
3.分析数据
(1)查看数据类型
(2) 将字段datetime的类型转换为日期时间
bike.datetime=pd.to_datetime(data.datetime)
bike.dtypes
(3)将datetime设置为索引,并从租赁数值差异着手观察它们的密度分布(从观察结果发现,有长尾现象)
bike=bike.set_index("datetime")
sns.distplot(bike["count"])
(4) 显示count的描述信息
(5)将count列中小于第一四分位数的数据删除,并绘制对应的密度图
def delete(x):
if x<145:
return np.nan
else:
return x
bike1=bike
bike1["count"]=bike["count"].apply(delete)
bike1=bike1.dropna(axis=0,how="any")
sns.distplot(bike1["count"])
(6)按年份统计自行车租赁数的均值,并画图
bike=bike1
y_bike=bike.groupby(bike.index.year).mean()["count"]
y_bike.plot(kind="bar",rot=0)
(7)重采样,按月进行分析汇总,并按月统计数据的绘图
m_bike=bike.resample('M',kind='period').mean()
m_bike.head(10)
m_bike.plot()
plt.legend(loc="best",fontsize=8)
(8)绘图观察哪个月的自行车租赁数目最大(九月份数量最多)
m_bike=bike.groupby(bike.index.month).mean()["count"]
m_bike.plot()
plt.grid()
(9) 分析每天不同时间自行车租赁数量的变化 (每天8点到17点自行车租数量最多)
h_bike=bike.groupby(bike.index.hour).mean()["count"]
h_bike.plot(kind="bar",rot=0)
(10)分析天气对租赁数额的影响
weather_bike=bike.groupby(bike.weather).mean()["count"]
plt.xlabel("weather")
plt.ylabel("number")
weather_bike.plot(kind="bar",rot=0)