美文网首页Python学习快车
共享单车项目的Python可视化分析,教你成为数据分析大师!

共享单车项目的Python可视化分析,教你成为数据分析大师!

作者: 松珏 | 来源:发表于2019-01-03 14:37 被阅读2次

    Python对数据的处理能力,很多人是抱着一定的怀疑的,不过在看完这篇文章之后,我相信你一定不会再怀疑的。

    一、背景:

    共享单车想必大家一定不会陌生,共享单车在国内的兴起,应该是2014年ofo的创立。截止到2017年3月,中国共享单车数量已经达到400万辆,成为大城市居民出行的重要交通工具。 在kaggle网站上的共享单车项目,它提供了美国某城市的共享单车2011年到2012年的数据集。该数据集包括了租车日期,租车季节,租车天气,租车气温,租车空气湿度等数据。我们可以通过利用这些数据来进行分析,得出有用的结论。

    二、本次的目标

    我们通过对数据进行清洗,计算描述性统计数据,以此来实现可视化数据分析。

    三、数据收集与分析:

    1、数据来源Kaggle项目地址(由于平台不予许设外链接,所以只能发链接了,请见谅):

    http://link.zhihu.com/?target=https%3A//www.kaggle.com/c/bike-sharing-demand

    2、导入数据

    #导入numpy、pandas、matplotlib.pyplot、seaborn包

    import numpy as np

    import pandas as pd

    import matplotlib.pyplot as plt

    import seaborn as sns

    #matplotlib.pyplot图表风格设定

    plt.style.use('ggplot')

    #命令行显示图表

    %matplotlib inline

    #忽略提示警告

    import warnings

    warnings.filterwarnings('ignore')

    本项目利用数据可视化进行分析,只用到train数据源。

    #导入数据

    train=pd.read_csv('train.csv')

    3、数据信息查看

    #显示前5行

    train.head(5)

    train数据源字段:

    datetime:时间 - 年月日小时

    season:季节 - 1 = spring春天, 2 = summer夏天, 3 = fall秋天, 4 = winter冬天

    holiday:节假日 - 0 = 否,1 = 是

    workingday:工作日 - 该天既不是周末也不是假日(0 = 否,1 = 是)

    weather:天气 - 1 = 晴天,2 = 阴天 ,3 = 小雨或小雪 ,4 = 恶劣天气(大雨、冰雹、暴风雨或者大雪)

    temp:实际温度

    atemp:体感温度

    humidity:湿度

    windspeed:风速

    casual:未注册用户租借数量

    registered:注册用户租借数量

    count:总租借数量

    #描述统计

    train.describe()

    四、数据清洗

    #字段信息描述

    train.info()

    RangeIndex: 10886 entries, 0 to 10885

    Data columns (total 12 columns):

    datetime 10886 non-null object

    season 10886 non-null int64

    holiday 10886 non-null int64

    workingday 10886 non-null int64

    weather 10886 non-null int64

    temp 10886 non-null float64

    atemp 10886 non-null float64

    humidity 10886 non-null int64

    windspeed 10886 non-null float64

    casual 10886 non-null int64

    registered 10886 non-null int64

    count 10886 non-null int64

    dtypes: float64(3), int64(8), object(1)

    memory usage: 1020.6+ KB

    train数据集无缺失数据,由于其中日期时间字段datetime精确到小时,为了进一步分析需要提取此字段信息,新增月、时、星期字段。

    #datetime改为日期格式

    train.datetime=pd.to_datetime(train.datetime,format='%Y-%m-%d %H:%M:%S')

    #提取年月日字段,格式YYYYmmdd

    train['datetime_D']=train.datetime.dt.strftime('%Y-%m-%d')

    train['datetime_D']=pd.to_datetime(train.datetime_D,format='%Y-%m-%d')

    #提取月份字段

    train['datetime_M']=train.datetime.dt.strftime('%Y%m')

    #提取小时字段

    train['datetime_H']=train.datetime.dt.strftime('%H')

    train['datetime_H']=train.datetime_H.astype('int')

    #提取星期字段

    train['datetime_W']=train.datetime.dt.strftime('%a')

    #将周一至周日改为1-7数字

    weekDict={'Mon':1,'Tue':2,'Wed':3,'Thu':4,'Fri':5,'Sat':6,'Sun':7}

    train.datetime_W=train.datetime_W.map(weekDict)

    train.info()

    RangeIndex: 10886 entries, 0 to 10885

    Data columns (total 16 columns):

    datetime 10886 non-null datetime64[ns]

    season 10886 non-null int64

    holiday 10886 non-null int64

    workingday 10886 non-null int64

    weather 10886 non-null int64

    temp 10886 non-null float64

    atemp 10886 non-null float64

    humidity 10886 non-null int64

    windspeed 10886 non-null float64

    casual 10886 non-null int64

    registered 10886 non-null int64

    count 10886 non-null int64

    datetime_D 10886 non-null datetime64[ns]

    datetime_M 10886 non-null object

    datetime_H 10886 non-null int32

    datetime_W 10886 non-null int64

    dtypes: datetime64[ns](2), float64(3), int32(1), int64(9), object(1)

    memory usage: 1.3+ MB

    #更新字段后查看train

    train.head(3)

    五、可视化分析数据

    1、相关系数热力图

    #热力图显示train数据集相关系数

    plt.figure(figsize=(11,11))

    sns.heatmap(train.corr(),linewidths=.1,annot=True)

    plt.title('共享单车相关系数')

    #X轴标准旋转45度

    plt.xticks(rotation=45,fontsize=15)

    plt.yticks(fontsize=15)

    (array([ 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5,

    9.5, 10.5, 11.5, 12.5]), )

    由热力图可得知:

    温度temp、体感问题atemp、小时datetime_H与租借数量count有较强正相关,其中温度/体感温度越高,骑车用户越多。

    湿度humidity与租借数量count有较强负相关,湿度越大,骑车用户越少。

    季节season、节假日holiday、工作日workingday、天气weather等字段由于是分类字段,这里相关系数较小。

    下面将从日期时间、天气情况、工作/节假日、用户4个角度进行可视化分析数据。

    2、日期时间分析

    #2011-2012年共享单车月租借数量走势

    fig=plt.figure(figsize=(14,4))

    ax1=fig.add_subplot(1,1,1)

    dataDf=pd.DataFrame(train.groupby(by='datetime_M').mean()['count']).reset_index()

    sns.pointplot(x='datetime_M',y='count',data=dataDf,ax=ax1)

    plt.title('2011-2012年共享单车月租借数量')

    plt.xlabel('日期')

    plt.xticks(rotation=45)

    plt.ylabel('租借数量(辆/时)')

    plt.grid(True)

    2011年至2012年共享单车租借数量呈曲线上升趋势,越来越多的人愿意使用共享单车,由于受温度、天气等因素影响,年中5到10月的使用者明显多于其他月份。

    #各时间段租借数量

    fig=plt.figure(figsize=(20,4))

    ax1=fig.add_subplot(1,2,1)

    dataDf=pd.DataFrame(train.groupby(by='datetime_H').mean()['count']).reset_index()

    sns.pointplot(x='datetime_H',y='count',data=dataDf,ax=ax1)

    plt.title('各时间段租借数量')

    plt.xlabel('时间')

    plt.ylabel('租借数量(辆/时)')

    plt.grid(True)

    #按星期租借数量

    ax2=fig.add_subplot(1,2,2)

    dataDf=pd.DataFrame(train.groupby(by='datetime_W').mean()['count']).reset_index()

    sns.pointplot(x='datetime_W',y='count',data=dataDf,ax=ax2)

    plt.title('按星期租借数量')

    plt.xlabel('星期')

    plt.ylabel('租借数量(辆/时)')

    plt.grid(True)

    每天8点、17到18点早晚上下班高峰共享单车的租借数量明显多于其他时间段,凌晨4点时租车辆达到最低。

    周六总租借数量最高,周日总租借数量最低。

    3天气角度分析

    #分析季节season、温度temp、体感温度atemp、租车辆count之间的关系

    sns.pairplot(train[['season','temp','atemp','count']],plot_kws={'alpha': 0.5},hue='season')

    春、冬、夏、秋4季温度依次升高,温度temp与体感温度atemp呈强正线性关系,可以理解字段temp近似于atemp。

    #不同季节租借数量对比

    fig=plt.figure(figsize=(14,4))

    ax1=fig.add_subplot(1,2,1)

    sns.violinplot(x='season',y='count',data=train,ax=ax1)

    plt.title('不同季节租借数量')

    plt.xlabel('季节')

    plt.ylabel('租借数量(辆/时)')

    #不同季节平均租借数量对比

    ax2=fig.add_subplot(1,2,2)

    sns.barplot(x='season',y='count',data=pd.DataFrame(train.groupby('season').mean()['count']).reset_index(),ax=ax2)

    plt.title('不同季节平均租借数量')

    plt.xlabel('季节')

    plt.ylabel('租借数量(辆/时)')

    结合上一张图表共同分析可知随着季节性温度的提高,租借数量也会随之增加,其中秋季温度最高共享单车使用者最多,而春季温度最低共享单车使用者最少。

    #不同天气租借数量对比

    plt.figure(figsize=(14,4))

    plt.subplot(1,2,1)

    sns.boxplot(x='weather',y='count',data=train)

    plt.title('不同天气租借数量')

    plt.xlabel('天气')

    plt.ylabel('租借数量(辆/时)')

    #不同天气平均租借数量对比

    plt.subplot(1,2,2)

    sns.barplot(x='weather',y='count',data=pd.DataFrame(train.groupby('weather').mean()['count']).reset_index())

    plt.title('不同天气平均租借数量')

    plt.xlabel('天气')

    plt.ylabel('租借数量(辆/时)')

    共享单车租借数量受天气因素影响较大,天气越恶劣租借的数量越少,大雪大雨天气下的租借数量接近为零。

    #temp可替代atemp,分析温度temp、湿度humidity、风速windspeed、租借数量count间的关系

    sns.pairplot(train[['temp','humidity','windspeed','count']],plot_kws={'alpha': 0.3})

    温度高于33度左右、低于15度左右租借数量明显减少。

    湿度大于70左右租借数量明显减少。

    风速大于20左右租借数量明显减少。

    温度高于27度左右风速及湿度均明显减少。

    train[['casual','registered']].sum().plot.pie(figsize=(5,5),autopct='%1.1f%%')

    租借共享单车的用户中注册用户占用户总数81.2%。

    fig=plt.figure(figsize=(14,4))

    ax1=fig.add_subplot(1,1,1)

    data1=pd.DataFrame(train.groupby('datetime_M').mean()[['casual','registered']]).reset_index()

    data2=pd.melt(data1,id_vars='datetime_M',value_vars=['casual','registered'])

    sns.pointplot(x='datetime_M',y='value',hue='variable',data=data2,ax=ax1)

    plt.title('2011-2012年非注册用户和注册用户租借数量')

    plt.xlabel('日期')

    plt.ylabel('租借数量(辆/时)')

    plt.xticks(rotation=45)

    plt.grid(True)

    2011-2012年非注册用户和注册用户的租借数量均呈曲线上升趋势,但注册用户的租借数量上升幅度远大于非注册用户的。

    fig=plt.figure(figsize=(16,4))

    ax1=fig.add_subplot(1,2,1)

    data1=pd.DataFrame(train.groupby('datetime_H').mean()[['casual','registered']])

    data1.plot(ax=ax1)

    plt.xticks(data1.reset_index().datetime_H)

    plt.title('非注册用户和注册用户各时间点租借数量')

    plt.xlabel('时间')

    plt.ylabel('租借数量(辆/时)')

    ax2=fig.add_subplot(1,2,2)

    data1=pd.DataFrame(train.groupby('datetime_W').mean()[['casual','registered']])

    data1.plot.bar(ax=ax2)

    plt.title('非注册用户和注册用户星期租借数量')

    plt.xticks(rotation=0)

    plt.xlabel('星期')

    plt.ylabel('租借数量(辆/时)')

    注册用户在每天8点、17到18点早晚上下班高峰租借数量明显高于其他时间段,而非注册用户无明显租借数量高峰。

    注册用户在周一至周五租借数量高于周末,而非注册用户情况相反。

    可分析得出注册用户大部分为上班族及学校师生,非注册用户为非上班族或自由职业等。

    fig=plt.figure(figsize=(12,10))

    ax1=fig.add_subplot(2,2,1)

    sns.barplot(x='holiday',y='casual',data=train,hue='holiday',ax=ax1)

    plt.title('非注册用户节假日时和非节假日租借数量')

    plt.xticks(rotation=0)

    plt.xlabel('时间')

    plt.ylabel('租借数量(辆/时)')

    ax2=fig.add_subplot(2,2,2)

    sns.barplot(x='holiday',y='registered',data=train,hue='holiday',ax=ax2)

    plt.title('注册用户节假日时和非节假日租借数量')

    plt.xticks(rotation=0)

    #plt.legend(loc='center')

    plt.xlabel('时间')

    plt.ylabel('租借数量(辆/时)')

    ax3=fig.add_subplot(2,2,3)

    sns.barplot(x='workingday',y='casual',data=train,hue='workingday',ax=ax3)

    plt.title('非注册用户工作日和非工作日租借数量')

    plt.xticks(rotation=0)

    plt.xlabel('时间')

    plt.ylabel('租借数量(辆/时)')

    ax4=fig.add_subplot(2,2,4)

    sns.barplot(x='workingday',y='registered',data=train,hue='workingday',ax=ax4)

    plt.title('注册用户工作日和非工作日租借数量')

    plt.xticks(rotation=0)

    #plt.legend(loc='center')

    plt.xlabel('时间')

    plt.ylabel('租借数量(辆/时)')

    非注册用户在节假日租借数量高于非节假日,非工作日租借数量高于工作日。

    注册用户相反,在节假日租借数量低于非节假日,非工作日租借数量低于工作日。

    通过以上的分析与得出的结论,大家对Python处理数据的能力是不是有所肯定呢?本文到此就要告一段落了,喜欢的小伙伴可以转发并点波关注!

    写在最后:

    又是新的一年,在这里小编没什么其他的东西送给大家的东西,好在手里还有一波Python的学习资料,有需要的朋友,可以加群571799375,我将免费送给大家!

    本文来自网络,如有侵权,请联系小编删除!

    相关文章

      网友评论

        本文标题:共享单车项目的Python可视化分析,教你成为数据分析大师!

        本文链接:https://www.haomeiwen.com/subject/pnvfrqtx.html