在Scala/Spark中,如何将空字符串(例如“ ”)转换为“NULL”?需要先修剪它,然后再将其转换为“NULL”。谢谢。
dataframe.na.replace("cut", Map(" " -> "NULL")).show //wrong
dataframe.na.replace("cut", Map(" " -> "NULL")).show //wrong
import org.apache.spark.sql.functions.{trim, length, when}
import org.apache.spark.sql.Column
def emptyToNull(c: Column) = when(length(trim(c)) > 0, c)
最后进行一个快速测试:
val df = Seq(" ", "foo", "", "bar").toDF
df.withColumn("value", emptyToNull($"value"))
应该会产生以下结果:
+-----+
|value|
+-----+
| null|
| foo|
| null|
| bar|
+-----+
如果您想将空字符串替换为字符串"NULL
,您可以添加otherwise
语句:
def emptyToNullString(c: Column) = when(length(trim(c)) > 0, c).otherwise("NULL")
import org.apache.spark.sql.functions.trim