web-dev-qa-db-ja.com

Spark他の列(行)に存在する場合、列文字列を置換

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は次のようになります。

enter image description here

8
Karol Sudol

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

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, '')"))
8
hi-zir