PySpark 之 flatMap

1. pyspark 版本

       2.3.0版本

 

2. 官網

 flatMap(fpreservesPartitioning=False)[source]

     Return a new RDD by first applying a function to all elements of this RDD, and then flattening the results.

   中文翻譯: 首先向該RDD的所有元素應用函數,然後將結果展平,以返回新的RDD。

>>> rdd = sc.parallelize([2, 3, 4])
>>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())
[1, 1, 1, 2, 2, 3]
>>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect())
[(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)]

 

3. 我的代碼

  案列1

from pyspark import SparkContext, SparkConf
conf = SparkConf().setMaster("local").setAppName("flatMap")
sc = SparkContext(conf=conf)
rdd1 = sc.parallelize(['hello', 'You are very good'])
new_rdd1 = rdd1.flatMap(lambda x: x.split())
print('new_rdd1 = ', new_rdd1.collect())


>>> new_rdd1 =  ['hello', 'You', 'are', 'very', 'good']

 案列2

rdd2 = sc.parallelize([['a', 'b'], ['d', 'c']])
new_rdd2 = rdd2.flatMap(lambda x:x)
print('new_rdd2 = ', new_rdd2.collect())
# flatMap 與 map 的區別:flatMap 是將所有元素全部展開,而map是做用於所有元素,意思是不給方法不給操作,原樣輸出
map_rdd = rdd2.map(lambda x:x)
print('map_rdd = ', map_rdd.collect())

>>> new_rdd2 =  ['a', 'b', 'd', 'c']
>>> map_rdd =  [['a', 'b'], ['d', 'c']]

4. flatMap 和 map 的區別

      map:對集合中每個元素進行操作。 
      flatMap:對集合中每個元素進行操作然後再扁平化。 

    詳細的解釋: https://blog.csdn.net/WYpersist/article/details/80220211

 

5. notebook

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章