PySpark数据科学入门
PySpark是一种很好的语言,可以大规模地进行探索性数据分析、构建机器学习管道以及为数据平台创建ETL。如果您已经熟悉Python和Pandas等库,那么PySpark是一种很好的语言,可以用来创建更具扩展性的分析和管道。这篇文章的目的是展示如何启动和运行PySpark并执行常见任务。
我们将使用Databricks作为Spark环境,将Kaggle的NHL数据集用作分析的数据源。这篇文章展示了如何在Spark 数据帧写入数据,创建这些帧的转换和聚合,可视化结果以及执行线性回归。我还将展示如何使用Pandas UDF以可扩展的方式将常规Python代码与PySpark混合。为了简单起见,我们将专注于批处理并避免流数据管道出现的一些复杂问题。
这篇文章的完整笔记本可以在github上找到。(https://github.com/bgweber/StartupDataScience/blob/master/EDA/PySpark_NHL.ipynb)
环境
启动和运行Spark有许多不同的选项:
- 自托管:您可以使用裸机或虚拟机自行设置群集。 Apache Ambari是这个选项的一个有用的项目,但它不是我推荐的快速启动和运行的方法。
- 云提供商:大多数云提供商都提供Spark集群:AWS具有EMR,GCP具有DataProc,它可以比自托管更快地进入互动环境。
- 供应商解决方案:包括Databricks和Cloudera在内的公司提供Spark解决方案,使Spark易于启动和运行。
使用的解决方案因安全性、成本和现有基础架构而异。如果您正在尝试使用并运行一个需要的环境来学习,那么我建议您使用Databricks Community Edition。
在Databricks Community Edition中创建PySpark集群
使用此环境,可以轻松启动并运行Spark群集和笔记本环境。在本教程中,我使用Spark 2.4运行时和Python 3创建了一个集群。要运行本文中的代码,您至少需要Spark版本2.3,才能获得Pandas UDF功能。
Spark 数据帧
PySpark中使用的关键数据类型是Spark 数据帧。此对象可以被视为分布在集群中的表,其功能类似于R和Pandas中的数据帧。如果你想使用PySpark进行分布式计算,那么你需要对Spark 数据帧执行操作,而不是其他python数据类型。
使用Spark时,也可以通过在Spark数据帧上调用toPandas()来使用Pandas数据帧,该数据帧返回一个pandas对象。但是,除了处理小型数据帧之外,通常应该避免使用此函数,因为它将整个对象拉入单个节点的内存中。
Pandas和Spark数据帧之间的主要区别之一是急切执行和延迟执行。在PySpark中,操作被延迟,直到管道中实际需要结果。例如,您可以指定从S3加载数据集并对数据帧应用多个转换的操作,但不会立即应用这些操作。相反,记录转换图,并且一旦实际需要数据,例如当将结果写回S3时,则转换被应用为单个管道操作。此方法用于避免将完整数据帧拉入内存,并在整个计算机集群中实现更有效的处理。使用Pandas数据帧,一切都被拉入内存,并立即应用每个Pandas操作。
通常,如果可能的话,最好避免在Spark中进行急切操作,因为它限制了有效分配的管道数量。
阅读数据
使用Spark时学习的第一步是将数据集加载到数据帧中。将数据加载到数据帧后,您可以应用转换、执行分析和建模,创建可视化并保留结果。在Python中,您可以使用Pandas直接从本地文件系统加载文件:
在PySpark中,加载CSV文件要复杂一些。在分布式环境中,没有本地存储,因此需要使用分布式文件系统(如HDFS,Databricks文件存储(DBFS)或S3)来指定文件的路径。
通常,在使用PySpark时,我使用S3中的数据。许多数据库都提供了对S3功能的卸载,并且还可以使用AWS控制台将文件从本地计算机移动到S3。对于这篇文章,我将使用Databricks文件系统(DBFS),它以/ FileStore的形式提供路径。第一步是上传您要处理的CSV文件。
将文件上载到Databricks文件