设为首页|收藏本站|
开启左侧

[问答] 案例:用 Xorbits 探索纽约出租车数据

[复制链接]
62429 0
雨灵蝶 发表于 2023-3-6 10:58:12 | 只看该作者 打印 上一主题 下一主题
 
Xorbits 是探索和分析大型数据集的理想工具。本文将用数据领域经典的数据集,纽约出租车数据,来展示 Xorbits 的能力。该数据集记录了 2009 年至 2022 年纽约出租车行程记录。我们将展示如何使用 Xorbits 对纽约出租车数据进行一些初始的探索。
您也可以选择用 Google Colab 或 Kaggle 并直接运行本案例。
案例的原始代码以及更多其他案例,请见 Xorbits Examples。
安装 Xorbits 及相关依赖

# 安装依赖
pip install xorbits>=0.1.2 plotly==5.11.0 pyarrow下载数据集

我们将会使用下列两个数据集:

  • 纽约出租车行驶记录
  • 纽约出租车区域划分
下载纽约出租车区域信息(区域划分与相关地理信息):
wget https://d37ci6vzurychx.cloudfront.net/misc/taxi+_zone_lookup.csv
wget https://data.cityofnewyork.us/api/geospatial/d3c5-ddgc\?method\=export\&format\=GeoJSON -O taxi_zones.geojson下载 2021 年纽约出租车行驶记录:
for i in {1..12}
do
    wget https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2021-$(printf "%02d" $i).parquet
done
mkdir yellow_tripdata_2021
mv yellow_tripdata_2021-*.parquet yellow_tripdata_2021初始化 Xorbits

首先,初始化 Xorbits:
import xorbits

# Initialize Xorbits in the local environment.
xorbits.init()数据加载

第二步,将数据加载到 Xorbits DataFrame 中。我们可以使用 read_parquet() 函数来完成,该函数允许我们指定 Parquet 文件的位置和在读取数据时要使用的其他选项,如密钥等。
加载纽约出租车行驶记录并清理错误数据:
import datetime
import xorbits.pandas as pd

trips = pd.read_parquet(
    'yellow_tripdata_2021',
    columns=[
        'tpep_pickup_datetime',
        'tpep_dropoff_datetime',
        'trip_distance',
        'PULocationID',
        'DOLocationID',
    ])
# Remove outliers.
trips = trips[(trips['tpep_pickup_datetime'] >= datetime.datetime(2021, 1, 1)) & (trips['tpep_pickup_datetime'] <= datetime.datetime(2021, 12, 31))]加载后的数据如下:
tpep_pickup_datetimetpep_dropoff_datetimetrip_distancePULocationIDDOLocationID
02021-01-01 00:30:102021-01-01 00:36:122.1014243
12021-01-01 00:51:202021-01-01 00:52:190.20238151
..................
32126462021-12-30 23:28:002021-12-30 23:43:004.4624687
32126722021-12-31 00:00:002021-12-31 00:08:001.02163229
加载纽约出租车区域数据:
taxi_zones = pd.read_csv('taxi+_zone_lookup.csv', usecols=['LocationID', 'Zone'])
taxi_zones.set_index(['LocationID'], inplace=True)加载后的数据如下:
LocationIDZone
1Newark AIrport
2Jamaica Bay
......
264NV
265NaN
最后加载出租车区域的地理信息:
import json
with open('taxi_zones.geojson') as fd:
    geojson = json.load(fd)初始探索

将数据加载到 DataFrame 后,我们可能希望通过查看行数和列数、每列的数据类型以及数据的前几行来了解数据的整体结构。 我们可以分别使用shape、dtypes和head()来实现:
trips.shape

(30833535, 5)
trips.dtypes

tpep_pickup_datetime     datetime64[ns]
tpep_dropoff_datetime    datetime64[ns]
trip_distance                   float64
PULocationID                      int64
DOLocationID                      int64
dtype: object
trips.head()
tpep_pickup_datetimetpep_dropoff_datetimetrip_distancePULocationIDDOLocationID
02021-01-01 00:30:102021-01-01 00:36:122.1014243
12021-01-01 00:51:202021-01-01 00:52:190.20238151
22021-01-01 00:43:302021-01-01 01:11:0614.70132165
32021-01-01 00:15:482021-01-01 00:31:0110.60138132
42021-01-01 00:31:492021-01-01 00:48:214.946833
时序分析

分析纽约出租车数据集的一个角度是查看乘车数量如何随时间变化。一个特别有趣的分析是找出每个工作日每小时的乘车数量。 我们可以在 DataFrame 中创建两个额外的列,分别表示行程开始的星期和小时。然后,我们可以使用 groupby 方法按照星期几和小时分组数据,并计算每组的旅途数量。
trips['PU_dayofweek'] = trips['tpep_pickup_datetime'].dt.dayofweek
trips['PU_hour'] = trips['tpep_pickup_datetime'].dt.hour
gb_time = trips.groupby(by=['PU_dayofweek', 'PU_hour'], as_index=False).agg(count=('PU_dayofweek', 'count'))
PU_dayofweekPU_hourcount
00055630
10128733
............
166622123082
16762390842
然后,我们可以使用像 Plotly 这样的库来可视化时间序列数据。下面的图表显示了每小时的乘车次数。从图表中可以看出,人们更倾向于在下午出行。此外,在周末,人们通常倾向于晚归。
import plotly.express as px

b = px.bar(
    gb_time.to_pandas(),
    x='PU_hour',
    y='count',
    color='PU_dayofweek',
    color_continuous_scale='sunset_r',
)
b.show()
案例:用 Xorbits 探索纽约出租车数据 第1张图片

每小时的乘车次数

下面的图表显示了一周中每天的乘车次数。
b = px.bar(
    gb_time.to_pandas(),
    x='PU_dayofweek',
    y='count',
    color='PU_hour',
    color_continuous_scale='sunset_r',
)
b.show()
案例:用 Xorbits 探索纽约出租车数据 第2张图片

一周中每天的乘车次数

空间分析

分析纽约出租车数据集的另一个角度是查看旅途的空间分布模式。我们可以使用groupby方法按旅途起点区域 ID 和下车地点区域 ID 将数据分组,计算每组的旅途数量,并可视化:
gb_pu_location = trips.groupby(['PULocationID'], as_index=False).agg(count=('PULocationID', 'count'))
gb_pu_location = gb_pu_location.to_pandas()

import plotly.graph_objects as go

fig = go.Figure(
    go.Choroplethmapbox(
        geojson=geojson,
        featureidkey='properties.location_id',
        locations=gb_pu_location['PULocationID'],
        z=gb_pu_location['count'],
        colorscale="Viridis",
        marker_opacity=0.7,
        marker_line_width=0.1
    )
)
fig.update_layout(
    mapbox_style="carto-positron",
    mapbox_zoom=9,
    mapbox_center = {"lat": 40.7158, "lon": -73.9805},
    height=600,
)
fig.show()
案例:用 Xorbits 探索纽约出租车数据 第3张图片

旅途起点的空间分布

我们还可以按下车地点区域 ID 对数据进行分组,并可视化:
gb_do_location = trips.groupby(['DOLocationID'], as_index=False).agg(count=('DOLocationID', 'count'))
gb_do_location = gb_do_location.to_pandas()

fig = go.Figure(
    go.Choroplethmapbox(
        geojson=geojson,
        featureidkey='properties.location_id',
        locations=gb_do_location['DOLocationID'],
        z=gb_do_location['count'],
        colorscale="Viridis",
        marker_opacity=0.7,
        marker_line_width=0.1
    )
)
fig.update_layout(
    mapbox_style="carto-positron",
    mapbox_zoom=9,
    mapbox_center = {"lat": 40.7158, "lon": -73.9805},
    height=600,
)
fig.show()
案例:用 Xorbits 探索纽约出租车数据 第4张图片

下车地点的空间分布

我们还可以探索出租车区域之间的交通情况:
gb_pu_do_location = trips.groupby(['PULocationID', 'DOLocationID'], as_index=False).agg(count=('PULocationID', 'count'))

# Add zone names.
gb_pu_do_location = gb_pu_do_location.merge(taxi_zones, left_on='PULocationID', right_index=True)
gb_pu_do_location.rename(columns={'Zone': 'PUZone'}, inplace=True)
gb_pu_do_location = gb_pu_do_location.merge(taxi_zones, left_on='DOLocationID', right_index=True)
gb_pu_do_location.rename(columns={'Zone': 'DOZone'}, inplace=True)

gb_pu_do_location.sort_values(['count'], inplace=True, ascending=False)
PULocationIDDOLocationIDcountPUZoneDOZone
44108237236225931Upper East Side SouthUpper East Side North
43855236237194655Upper East Side NorthUpper East Side South
..................
8689291AuburndaleBrighton Beach
493372641051NVGovernor's Island/Ellis Island/Liberty Island
总结

正如我们在本文中使用纽约市出租车数据集所展示的,Xorbits 是一种极其强大的用于探索和分析大型数据集的工具。 通过按照本文中所述的步骤,您可以更好地了解 Xorbits 的功能、易用性,以及如何将其与其他 Python 库集成,以简化您的数据分析工作流程。
如果你对 Xorbits 感兴趣,那么事不宜迟,快来试用吧!
资料


  • 官方网站:https://xorbits.cn
  • Github:https://github.com/xprobe-inc/xorbits
  • Gitee:https://gitee.com/xprobe-inc/xorbits
  • 文档:https://doc.xorbits.cn
  • 社区:https://xorbits.cn/community



上一篇:喜大普奔!春节成纽约市法定假日!
下一篇:盘点纽约的安全“绿灯区”
@



1.西兔生活网 CTLIVES 内容全部来自网络;
2.版权归原网站或原作者所有;
3.内容与本站立场无关;
4.若涉及侵权或有疑义,请点击“举报”按钮,其他联系方式或无法及时处理。
 
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

排行榜
活跃网友
返回顶部快速回复上一主题下一主题返回列表APP下载手机访问
Copyright © 2016-2028 CTLIVES.COM All Rights Reserved.  西兔生活网  小黑屋| GMT+8, 2024-4-30 12:30