python - Databricks 火花 UDF 不适用于过滤的数据帧
问题描述
我在使用 Pyspark 的 Databricks 中遇到了一个问题,如果我在这里遗漏了一些概念性的东西,我试图理解为什么这个实现不起作用。我要做的是在数据框中的列上运行 UDF,但只能在非空值上运行。
如果我将 lstrip_udf 调用替换为“Val123”之类的固定值,那么它可以正常工作,但它不适用于 UDF。如果我在 UDF 中使用不同的实现方式实现空值检查,那么它也可以工作。但即使有when和IsNotNull它仍然会引发以下错误。
有人可以解释为什么或我在这里缺少什么来完成这项工作吗?
代码:
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, BooleanType, TimestampType
inputschema = StructType([StructField("testcol", StringType(), True),
StructField("testcol2", StringType(), True)
]
)
inputfile = spark.createDataFrame([("012121212","Ref #1"),
("0034343434","Ref #2"),
("0034343434","Ref #3"),
(None,"Ref #4"),
(None,"Ref #5"),
("00998877","Ref #6")
],
schema = inputschema
)
#display(inputfile)
from pyspark.sql.functions import col, when, lit
column_name = "testcol"
lstrip_udf = udf(lambda s: s.lstrip().lstrip("0"), StringType())
outputfile = (inputfile.withColumn(column_name,
when(col(column_name).isNotNull(),
lstrip_udf(col(column_name)) #replace this line with "Val123" and it works
)
))
display(outputfile)
错误:
File "<command-3701821159856508>", line 18, in <lambda>
AttributeError: 'NoneType' object has no attribute 'lstrip'
谢谢
解决方案
这可能是 Spark 中的一个错误,所以这里是对 UDF 的一个小修改,它解决了这个问题:
lstrip_udf = udf(lambda s: s.lstrip().lstrip("0") if s is not None else None, StringType())
或者您可以使用 Spark SQL 来执行此操作,这比使用 UDF 更有效:
outputfile = (
inputfile.withColumn(column_name,
F.when(col(column_name).isNotNull(),
F.expr("ltrim('0', ltrim('',testcol))")
)
)
)
推荐阅读
- azure - Azure Pipelines:对 Azure AD 身份验证后的 Azure Function/Web 应用程序使用带有 HTTP 请求的 Release Gate
- spring - RedisTemplate `execute` 类型不匹配
- sql - 如何裁剪 json
- excel-formula - excel中的索引匹配功能
- c++ - 尝试将 WinForms 按钮映射到新表单时不断出错(使用 Visual Studio 和 C++)
- sql - 通过报告页面传递参数 - Google 数据洞察
- regex - 在 PSI 预览模式下无法识别 intellij 语法工具包 BNF 语法中的字符串和字符标记
- photoshop - What is the real width of the document in Photoshop?
- xml - How do I resolve the problem "xmlns" must be declared for element type "beans"?
- python - PyQt5 中的 QTableWidget 上永远不会出现水平滚动条