python - 用于在 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,
三个元素中的每一个都相应地表示
- 日期
- 标签
- 评论
我需要应用过滤器转换,以便仅保留以“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()
解决方案
您收到错误消息:
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))
让我知道这是否适合您。
推荐阅读
- c - 为什么 scanf 在使用 C 编程的函数中不起作用?
- c++ - 如何将对象类型转换为 int c++
- asp.net - AWS 上的 ASP.NET Core 前端和 REST 与 Fargate 和 API Gateway
- python - 如何在数据结构列表中优雅地绘制特定成员?
- sql - 每年、每月、每季度或每周过滤记录
- c++ - 对于 x86_64、arm 或其他拱门,11 是 ISO c++ 下的有效输出吗?
- go - 解析前更改布尔标志的值
- javascript - 我如何在javascript中编写承诺
- bash - 使用 bash 从数组中提取匹配字符串的最佳方法
- r - 当用户输入的值发生变化时,在 Shiny Dashboard 中的 ggplot 中显示动态百分比和数量值