Flatmap 和map 区别
map将函数作用到数据集的每一个元素上,生成一个新的分布式的数据集(RDD)返回
map函数的源码:
def map(self, f, preservesPartitioning=False): """ Return a new RDD by applying a function to each element of this RDD. >>> rdd = sc.parallelize(["b", "a", "c"]) >>> sorted(rdd.map(lambda x: (x, 1)).collect()) [('a', 1), ('b', 1), ('c', 1)] """ def func(_, iterator): return map(fail_on_stopiteration(f), iterator) return self.mapPartitionsWithIndex(func, preservesPartitioning)
map将每一条输入执行func操作并对应返回一个对象,形成一个新的rdd,如源码中的rdd.map(lambda x: (x, 1) --> [('a', 1), ('b', 1), ('c', 1)]
flatMap会先执行map的操作,再将所有对象合并为一个对象,返回值是一个Sequence
flatMap源码:
def flatMap(self, f, preservesPartitioning=False): """ >>> 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)] """ def func(s, iterator): return chain.from_iterable(map(fail_on_stopiteration(f), iterator)) return self.mapPartitionsWithIndex(func, preservesPartitioning)
注意:flatMap将输入执行func操作时,对象必须是可迭代的
map与flatMap的区别:
1 from pyspark import SparkConf, SparkContext 2 3 conf = SparkConf() 4 sc = SparkContext(conf=conf) 5 6 7 def func_map(): 8 data = ["hello world", "hello fly"] 9 data_rdd = sc.parallelize(data) 10 map_rdd = data_rdd.map(lambda s: s.split(" ")) 11 print("map print:{}".format(map_rdd.collect())) 12 13 14 def func_flat_map(): 15 data = ["hello world", "hello fly"] 16 data_rdd = sc.parallelize(data) 17 flat_rdd = data_rdd.flatMap(lambda s: s.split(" ")) 18 print("flatMap print:{}".format(flat_rdd.collect())) 19 20 21 func_map() 22 func_flat_map() 23 sc.stop()
执行结果:
map print:[['hello', 'world'], ['hello', 'fly']] flatMap print:['hello', 'world', 'hello', 'fly']
可以看出,map对 "hello world", "hello fly"这两个对象分别映射为['hello', 'world'], ['hello', 'fly'],而flatMap在map的基础上做了一个合并操作,将这两个对象合并为一个['hello', 'world', 'hello', 'fly'],这就造就了flatMap在词频统计方面的优势。
标签:
spark
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】