将 Spark 数据框中的所有“:”替换为“_”

Replace all ":" with "_" in Spark dataframe

我正在尝试替换 Spark 数据帧的单个列中“:”-->“_”的所有实例。我正在尝试这样做:

val url_cleaner = (s:String) => {
   s.replaceAll(":","_")
}
val url_cleaner_udf = udf(url_cleaner)
val df = old_df.withColumn("newCol", url_cleaner_udf(old_df("oldCol")) )

但我一直收到错误消息:

 SparkException: Job aborted due to stage failure: Task 0 in stage 25.0 failed 4 times, most recent failure: Lost task 0.3 in stage 25.0 (TID 692, ip-10-81-194-29.ec2.internal): java.lang.NullPointerException

udf 哪里出错了?

可能您在此列中有一些空值。

尝试:

val urlCleaner = (s:String) => {
   if (s == null) null else s.replaceAll(":","_")
}

你也可以使用regexp_replace(col("newCol"), ":", "_")代替自己的函数