谁能给我解释一下map和flatMap之间的区别,以及它们各自的良好用例是什么?
“flatten the results”是什么意思? 它有什么好处?
谁能给我解释一下map和flatMap之间的区别,以及它们各自的良好用例是什么?
“flatten the results”是什么意思? 它有什么好处?
当前回答
地图:
是一种高阶方法,它接受一个函数作为输入,并将其应用于源RDD中的每个元素。
http://commandstech.com/difference-between-map-and-flatmap-in-spark-what-is-map-and-flatmap-with-examples/
flatMap:
接受输入函数的高阶方法和转换操作。
其他回答
对于所有想要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()
[‘你好’,‘什么’,‘是’,‘你’,‘做’,‘这’,‘是’,‘爱’)
希望能有所帮助。
Flatmap和Map都转换集合。
的区别:
地图(函数) 返回一个新的分布式数据集,该数据集通过函数func传递源的每个元素。
flatMap(函数) 类似于map,但是每个输入项可以映射到0个或多个输出项(因此func应该返回Seq而不是单个项)。
变换函数为: map:输入一个元素->输出一个元素。 flatMap:输入一个元素->输出0个或更多元素(一个集合)。
这可以归结为你最初的问题:你所说的扁平化是什么意思?
当您使用flatMap时,“多维”集合就变成了“一维”集合。
val array1d = Array ("1,2,3", "4,5,6", "7,8,9")
//array1d is an array of strings
val array2d = array1d.map(x => x.split(","))
//array2d will be : Array( Array(1,2,3), Array(4,5,6), Array(7,8,9) )
val flatArray = array1d.flatMap(x => x.split(","))
//flatArray will be : Array (1,2,3,4,5,6,7,8,9)
当你想使用flatMap时,
你的地图功能的结果是创建多层结构 但所有你想要的是一个简单的-平面-一维结构,通过删除所有的内部分组
地图:
是一种高阶方法,它接受一个函数作为输入,并将其应用于源RDD中的每个元素。
http://commandstech.com/difference-between-map-and-flatmap-in-spark-what-is-map-and-flatmap-with-examples/
flatMap:
接受输入函数的高阶方法和转换操作。
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