col1
にあるcol2
から文字列を削除したい:
val df = spark.createDataFrame(Seq(
("Hi I heard about Spark", "Spark"),
("I wish Java could use case classes", "Java"),
("Logistic regression models are neat", "models")
)).toDF("sentence", "label")
regexp_replace
またはtranslate
refを使用: spark functions api
val res = df.withColumn("sentence_without_label", regexp_replace
(col("sentence") , "(?????)", "" ))
res
は次のようになります。
単にregexp_replace
を使用できます
df5.withColumn("sentence_without_label", regexp_replace($"sentence" , lit($"label"), lit("" )))
または、次のように簡単なUDF関数を使用できます
val df5 = spark.createDataFrame(Seq(
("Hi I heard about Spark", "Spark"),
("I wish Java could use case classes", "Java"),
("Logistic regression models are neat", "models")
)).toDF("sentence", "label")
val replace = udf((data: String , rep : String)=>data.replaceAll(rep, ""))
val res = df5.withColumn("sentence_without_label", replace($"sentence" , $"label"))
res.show()
出力:
+-----------------------------------+------+------------------------------+
|sentence |label |sentence_without_label |
+-----------------------------------+------+------------------------------+
|Hi I heard about Spark |Spark |Hi I heard about |
|I wish Java could use case classes |Java |I wish could use case classes|
|Logistic regression models are neat|models|Logistic regression are neat |
+-----------------------------------+------+------------------------------+
label
である場合、それは単なるリテラルです。
import org.Apache.spark.sql.functions._
df.withColumn("sentence_without_label",
regexp_replace(col("sentence"), col("label"), lit(""))).show(false)
+-----------------------------------+------+------------------------------+
|sentence |label |sentence_without_label |
+-----------------------------------+------+------------------------------+
|Hi I heard about Spark |Spark |Hi I heard about |
|I wish Java could use case classes |Java |I wish could use case classes|
|Logistic regression models are neat|models|Logistic regression are neat |
+-----------------------------------+------+------------------------------+
Spark 1.6では、expr
でも同じことができます。
df.withColumn(
"sentence_without_label",
expr("regexp_replace(sentence, label, '')"))