PySpark实战:repartition操作
来自CloudWiki
介绍
repartition操作是一个变换算子,
可以实现按数据进行重新分区的功能。
在重新分配过程中,可以增加或减少此RDD中的并行度
代码
import findspark findspark.init() ############################################## from pyspark.sql import SparkSession spark = SparkSession.builder \ .master("local[1]") \ .appName("RDD Demo") \ .getOrCreate(); sc = spark.sparkContext ############################################# rdd = sc.parallelize([1,2,3,4,5,6,7], 3) #[[1, 2], [3, 4], [5, 6, 7]] print(rdd.glom().collect()) #[[1, 2, 5, 6, 7], [3, 4]] print(rdd.repartition(2).glom().collect()) #[[], [1, 2], [], [], [5, 6, 7], [3, 4]] print(rdd.repartition(6).glom().collect()) ############################################## sc.stop()
- 如果要减少此RDD中的分区数,请考虑使用coalesc进行操作,这样可以避免执行shuffle操作,效率也更高
输出
[[1, 2], [3, 4], [5, 6, 7]]
[[1, 2, 5, 6, 7], [3, 4]]
[[], [1, 2], [], [], [5, 6, 7], [3, 4]]