user1615666 user1615666 - 1 year ago 349
Scala Question

spark dataframe trim column and convert

In Scala / Spark, how to convert empty string, like " ", to "NULL" ? need to trim it first and then convert to "NULL". Thanks."cut", Map(" " -> "NULL")).show //wrong

Answer Source

You can create a simple function to do it. First a couple of imports:

import org.apache.spark.sql.functions.{trim, length, when}
import org.apache.spark.sql.Column

and the definition:

def emptyToNull(c: Column) = when(length(trim(c)) > 0, c)

Finally a quick test:

val df = Seq(" ", "foo", "", "bar").toDF
df.withColumn("value", emptyToNull($"value"))

which should yield following result:

| null|
|  foo|
| null|
|  bar|
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download