首页 > 解决方案 > 用于在 Spark(Python)中过滤 RDD 的 Lambda 函数 - 检查元素是否不是空字符串

问题描述

我有以下 RDD

2019-09-24,Debt collection,transworld systems inc. is trying to collect a debt that is not mine not owed and is inaccurate.

2019-09-19,Credit reporting credit repair services or other personal consumer reports,

三个元素中的每一个都相应地表示

  1. 日期
  2. 标签
  3. 评论

我需要应用过滤器转换,以便仅保留以“201”开头的记录(用于日期)并包含注释(它们具有值并且在第三个元素中不是空字符串)。

我正在使用以下代码来计算每次从过滤转换中减少了多少记录:

countA = rdd.count()

countB = rdd.filter(lambda x: x.startswith('201')).count()

countC = rdd.filter(lambda x: x.startswith('201') & (x.split(",")[2] != None) & (len(x.split(",")[2]) > 0)).count()

我的代码在计算时崩溃了countC,尽管在我的进一步计算中过滤似乎起作用了,但我也得到了更多的错误...... 在此处输入图像描述

标签: pythonapache-sparklambdardd

解决方案


您收到错误消息:

IndexError:列表索引超出范围

因为您正在尝试访问2列表的索引(拆分的结果),如果数据集中的某些行只有日期或日期和标签,或者为空或可能存在格式问题,则该索引可能不存在。

在您的 lambda 函数中,您可以利用 python 中的短路来首先检查是否有至少 3 个元素(即2可以使用len(x.split(",")) >=3而不是 的索引(x.split(",")[2] != None)),然后再尝试访问该索引。

这可以写成:

countC = rdd.filter(lambda x: x.startswith('201') and (len(x.split(",")) >=3) and (len(x.split(",")[2]) > 0))

让我知道这是否适合您。


推荐阅读