Spark中map与flatMap

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):
    """
    Return a new RDD by first applying a function to all elements of this
    RDD, and then flattening the results.
    >>> 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的区别:

from pyspark import SparkConf, SparkContext
 
conf = SparkConf()
sc = SparkContext(conf=conf)
 
 
def func_map():
    data = ["hello world", "hello fly"]
    data_rdd = sc.parallelize(data)
    map_rdd = data_rdd.map(lambda s: s.split(" "))
    print("map print:{}".format(map_rdd.collect()))
 
 
def func_flat_map():
    data = ["hello world", "hello fly"]
    data_rdd = sc.parallelize(data)
    flat_rdd = data_rdd.flatMap(lambda s: s.split(" "))
    print("flatMap print:{}".format(flat_rdd.collect()))
    
    
func_map()
func_flat_map()
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在词频统计方面的优势。

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值