大数据:并行计算入门-PySpark的使用

1,752 阅读2分钟

Spark应用程序作为独立的进程集运行,由驱动程序中的Spark context进行协调。

它可以自动创建(例如,如果您从shell中调用pyspark(然后将Spark上下文称为sc)。

但是我们还没有建立它,所以需要进行定义:

from pyspark import SparkContext
sc = SparkContext('local[2]', 'Spark 101')

如果想要使用全部可用资源,也可以使用:

sc = SparkContext('local[*]', 'Spark 101')

创建完之后,首先处理一个简单的摄氏华氏温度转换的并行计算

temp_c = [10, 3, -5, 25, 1, 9, 29, -10, 5]
​
rdd_temp_c = sc.parallelize(temp_c)
rdd_temp_K = rdd_temp_c.map(lambda x: x + 273.15).collect()
​
print(rdd_temp_K)

结果

[283.15, 276.15, 268.15, 298.15, 274.15, 282.15, 302.15, 263.15, 278.15]

通过使用sc.parallelize来并行处理待计算的摄氏温度,然后使用map来进行一一映射。

除了map这种映射外,常用还有reduce函数,例如

numbers = [1, 4, 6,2, 9, 10]
​
rdd_numbers=sc.parallelize(numbers)
​
# Use reduce to combine numbers
rdd_reduce = rdd_numbers.reduce(lambda x,y: "(" + str(x) + ", " + str(y) + "]")
#rdd_reduce = rdd_numbers.reduce(lambda x,y: "(" + str(x) + str(y))
​
​
print(rdd_reduce)

结果

(((1, (4, 6]], 2], (9, 10]]

通常我们使用PySpark是为了部署机器学习项目,在PySpark中也有多样的数据处理手段。

首先我们创建一个会话(Session)

from pyspark.sql import SparkSession
​
session = SparkSession.builder.appName('data_processing').getOrCreate()

读入数据集

df = session.read.csv('iris.csv',inferSchema=True,header=True)
df.show()
df.printSchema()

结果

root
 |-- sepal_length: double (nullable = true)
 |-- sepal_width: double (nullable = true)
 |-- petal_length: double (nullable = true)
 |-- petal_width: double (nullable = true)
 |-- species: string (nullable = true)

也可以选择指定列输出

df.select('sepal_width','petal_width').show(3)

结果

+-----------+-----------+
|sepal_width|petal_width|
+-----------+-----------+
|        3.5|        0.2|
|        3.0|        0.2|
|        3.2|        0.2|
+-----------+-----------+
only showing top 3 rows

创建新列

df.withColumn("new_col_name",(df["sepal_width"]*10)).show(6)

筛选特征

df.filter(df["species"]=="setosa").show(9)
df.filter((df["species"]=="setosa") | (df["sepal_width"]<3.0)).show(9)

查看列的不同值

df.select("species").distinct().show()

按列统计

df.groupBy('petal_length').count().show()

按列统计排序

df.groupBy('petal_length').count().orderBy("count",ascending=False).show()

按列聚合

df.groupBy('species').agg({'sepal_length':'sum'}).show()

以上只是简单的数据处理部分,PySpark还有很多其他吸引人的特性。

文源网络,仅供学习之用,如有侵权,联系删除。

我将优质的技术文章和经验总结都汇集在了我的公众号【Python圈子】里。

在学习Python的道路上肯定会遇见困难,别慌,我这里有一套学习资料,包含40+本电子书,600+个教学视频,涉及Python基础、爬虫、框架、数据分析、机器学习等,不怕你学不会!

file