evi*_*ish 5 apache-spark apache-spark-sql pyspark
假设您尝试从数据帧的列中提取子字符串。regexp_extract()
如果字段本身为 null,则返回 null;如果字段不为 null 但未找到表达式,则返回空字符串。对于后一种情况如何返回空值?
df = spark.createDataFrame([(None),('foo'),('foo_bar')], StringType())
df.select(regexp_extract('value', r'_(.+)', 1).alias('extracted')).show()
# +---------+
# |extracted|
# +---------+
# | null|
# | |
# | bar|
# +---------+
Run Code Online (Sandbox Code Playgroud)
我不确定是否regexp_extract()
可以返回None
String 类型。None
您可以做的一件事是使用用户定义的函数替换空字符串:
from pyspark.sql.functions import regexp_extract, udf
from pyspark.sql.types import StringType
df = spark.createDataFrame([(None),('foo'),('foo_bar')], StringType())
toNoneUDF = udf(lambda val: None if val == "" else val, StringType())
new_df = df.select(regexp_extract('value', r'_(.+)', 1).alias('extracted'))
new_df.withColumn("extracted", toNoneUDF(new_df.extracted)).show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7479 次 |
最近记录: |