谁能给我解释一下map和flatMap之间的区别,以及它们各自的良好用例是什么?
“flatten the results”是什么意思? 它有什么好处?
谁能给我解释一下map和flatMap之间的区别,以及它们各自的良好用例是什么?
“flatten the results”是什么意思? 它有什么好处?
当前回答
map:它通过对RDD的每个元素应用函数来返回一个新的RDD。.map中的函数只能返回一个项。
flatMap:与map类似,它通过对RDD的每个元素应用函数来返回一个新的RDD,但输出是扁平的。
同样,flatMap中的函数可以返回一个元素列表(0或更多)
例如:
sc.parallelize([3,4,5]).map(lambda x: range(1,x)).collect()
输出:[[1,2],[1,2,3],[1,2,3,4]]
sc.parallelize([3,4,5]).flatMap(lambda x: range(1,x)).collect()
输出:注意o/p在单个列表[1,2,1,2,3, 1,2,3,4]
来源:https://www.linkedin.com/pulse/difference-between-map-flatmap-transformations-spark-pyspark-pandey/
其他回答
map和flatMap输出的差异:
1. flatmap
val a = sc.parallelize(1 to 10, 5)
a.flatMap(1 to _).collect()
输出:
1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
2.地图:
val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
val b = a.map(_.length).collect()
输出:
3 6 6 3 8
抽样。Map返回单个数组中的所有元素
抽样。flatMap返回数组数组中的元素
让我们假设在text.txt文件中有文本
Spark is an expressive framework
This text is to understand map and faltMap functions of Spark RDD
使用地图
val text=sc.textFile("text.txt").map(_.split(" ")).collect
输出:
text: **Array[Array[String]]** = Array(Array(Spark, is, an, expressive, framework), Array(This, text, is, to, understand, map, and, faltMap, functions, of, Spark, RDD))
使用flatMap
val text=sc.textFile("text.txt").flatMap(_.split(" ")).collect
输出:
text: **Array[String]** = Array(Spark, is, an, expressive, framework, This, text, is, to, understand, map, and, faltMap, functions, of, Spark, RDD)
map(func)返回一个新的分布式数据集,该数据集通过func声明的函数传递源的每个元素。map()是单个项
其间
flatMap(func)类似于map,但是每个输入项可以映射到0个或多个输出项,因此func应该返回一个Sequence而不是单个项。
map和flatMap是相似的,从某种意义上说,它们从输入RDD中获取一行并在其上应用一个函数。它们的不同之处在于map中的函数只返回一个元素,而flatMap中的函数可以返回一个元素列表(0或更多)作为迭代器。
同样,flatMap的输出是扁平的。尽管flatMap中的函数返回一个元素列表,但flatMap返回一个RDD,其中以平面方式(而不是列表)包含列表中的所有元素。
对于所有想要PySpark相关的人:
示例转换:flatMap
>>> a="hello what are you doing"
>>> a.split()
['hello', 'what', 'are', 'you', 'doing']
>>> b=["hello what are you doing","this is rak"]
>>> b.split()
回溯(最近一次调用): 文件“”,第1行,在 AttributeError: 'list'对象没有属性'split'
>>> rline=sc.parallelize(b)
>>> type(rline)
>>> def fwords(x):
... return x.split()
>>> rword=rline.map(fwords)
>>> rword.collect()
[[‘你好’,‘什么’,‘是’,‘你’,‘做’],[‘这个’,‘是’,'爱你']]
>>> rwordflat=rline.flatMap(fwords)
>>> rwordflat.collect()
[‘你好’,‘什么’,‘是’,‘你’,‘做’,‘这’,‘是’,‘爱’)
希望能有所帮助。