use*_*666 8 scala apache-spark
在Scala/Spark中,如何将空字符串(如"")转换为"NULL"?需要先修剪它然后转换为"NULL".谢谢.
dataframe.na.replace("cut", Map(" " -> "NULL")).show //wrong
Run Code Online (Sandbox Code Playgroud)
您可以创建一个简单的功能来完成它.首先是几个进口:
import org.apache.spark.sql.functions.{trim, length, when}
import org.apache.spark.sql.Column
Run Code Online (Sandbox Code Playgroud)
和定义:
def emptyToNull(c: Column) = when(length(trim(c)) > 0, c)
Run Code Online (Sandbox Code Playgroud)
最后一个快速测试:
val df = Seq(" ", "foo", "", "bar").toDF
df.withColumn("value", emptyToNull($"value"))
Run Code Online (Sandbox Code Playgroud)
应产生以下结果:
+-----+
|value|
+-----+
| null|
| foo|
| null|
| bar|
+-----+
Run Code Online (Sandbox Code Playgroud)
如果您想更换空字符串与字符串 "NULL
,你可以添加otherwise
条款:
def emptyToNullString(c: Column) = when(length(trim(c)) > 0, c).otherwise("NULL")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10607 次 |
最近记录: |