Skip to main content
 首页 » 编程设计

python之从 Spark RDD 中移除元素

2024年10月24日29落叶

我正在从一个文本文件构建一个 RDD。有些行不符合我期望的格式,在这种情况下我使用标记 -1。

def myParser(line): 
    try: 
        # do something 
    except: 
        return (-1, -1), -1 
 
lines = sc.textFile('path_to_file') 
pairs = lines.map(myParser) 

是否可以删除带有 -1 标记的行?如果不是,解决方法是什么?

请您参考如下方法:

我能想到的最简洁的解决方案是使用 flatMap 丢弃格式错误的行:

def myParser(line): 
    try: 
        # do something 
        return [result] # where result is the value you want to return 
    except: 
        return [] 
 
sc.textFile('path_to_file').flatMap(myParser) 

另见 What is the equivalent to scala.util.Try in pyspark?

您还可以在 map 之后进行过滤:

pairs = lines.map(myParser).filter(lambda x: x != ((-1, -1), -1))