wake-up-neo.com

Spark Spaltenzeichenfolge ersetzen, wenn in einer anderen Spalte (Zeile) vorhanden

Ich möchte Zeichenfolgen aus col1 Entfernen, die in col2 Vorhanden sind:

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")

mit regexp_replace oder translate ref: Funkenfunktionen api

val res = df.withColumn("sentence_without_label", regexp_replace 
(col("sentence") , "(?????)", "" ))

so dass res wie folgt aussieht:

enter image description here

8
Karol Sudol

Sie könnten einfach regexp_replace

df5.withColumn("sentence_without_label", regexp_replace($"sentence" , lit($"label"), lit("" )))

oder Sie können die einfache udf-Funktion wie folgt verwenden

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()

Ausgabe:

+-----------------------------------+------+------------------------------+
|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 |
+-----------------------------------+------+------------------------------+
8
Shankar Koirala

Wenn label nur ein Literal ist, ist es ziemlich einfach:

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 |
+-----------------------------------+------+------------------------------+  

In Spark 1.6 können Sie dasselbe mit expr tun:

df.withColumn(
  "sentence_without_label",
  expr("regexp_replace(sentence, label, '')"))
8
hi-zir