[英]How to change the value of a column according to the value of another column in a spark DataFrame
我從這個 dataframe 開始
DF1
+----+-------+-------+-------+
|name | type |item1 | item2 |
+-----+-------+------+-------+
|apple|fruit |apple1|apple2 |
|beans|vege |beans1|beans2 |
|beef |meat |beef1 |beef2 |
|kiwi |fruit |kiwi1 |kiwi2 |
|pork |meat |pork1 |pork2 |
+-----+-------+--------------+
現在我想根據 DF2 中的“類型”列的列值填充一個名為“prop”的列。 例如,
If "type"== "fruit" then "prop"="item1"
If "type"== "vege" then "prop"="item1"
If "type"== "meat" then "prop"="item2"
得到這個的最好方法是什么? 我正在考慮根據每個“類型”進行過濾,填充“道具”列,然后連接生成的數據幀。 這似乎效率不高。
DF2
+----+-------+-------+-------+-------+
|name | type |item1 | item2 | prop |
+-----+-------+------+-------+-------+
|apple|fruit |apple1|apple2 |apple1 |
|beans|vege |beans1|beans2 |beans1 |
|beef |meat |beef1 |beef2 |beef2 |
|kiwi |fruit |kiwi1 |kiwi2 |kiwi1 |
|pork |meat |pork1 |pork2 |pork2 |
+-----+-------+--------------+-------+
在這種情況下使用when+otherwise
語句,這在Spark中非常有效。
//sample data
df.show()
//+-----+-----+------+------+
//| name| type| item1| item2|
//+-----+-----+------+------+
//|apple|fruit|apple1|apple2|
//|beans| vege|beans1|beans2|
//| beef| meat| beef1| beef2|
//| kiwi|fruit| kiwi1| kiwi2|
//| pork| meat| pork1| pork2|
//+-----+-----+------+------+
//using isin function
df.withColumn("prop",when((col("type").isin(Seq("vege","fruit"):_*)),col("item1")).when(col("type") === "meat",col("item2")).otherwise(col("type"))).show()
df.withColumn("prop",when((col("type") === "fruit") ||(col("type") === "vege"),col("item1")).when(col("type") === "meat",col("item2")).
otherwise(col("type"))).
show()
//+-----+-----+------+------+------+
//| name| type| item1| item2| prop|
//+-----+-----+------+------+------+
//|apple|fruit|apple1|apple2|apple1|
//|beans| vege|beans1|beans2|beans1|
//| beef| meat| beef1| beef2| beef2|
//| kiwi|fruit| kiwi1| kiwi2| kiwi1|
//| pork| meat| pork1| pork2| pork2|
//+-----+-----+------+------+------+
可以通過鏈接when
和otherwise
來完成,如下所示
import org.apache.spark.sql.functions._
object WhenThen {
def main(args: Array[String]): Unit = {
val spark = Constant.getSparkSess
import spark.implicits._
val df = List(("apple","fruit","apple1","apple2"),
("beans","vege","beans1","beans2"),
("beef","meat","beef1","beans2"),
("kiwi","fruit","kiwi1","beef2"),
("pork","meat","pork1","pork2")
).toDF("name","type","item1","item2" )
df.withColumn("prop",
when($"type" === "fruit", $"item1").otherwise(
when($"type" === "vege", $"item1").otherwise(
when($"type" === "meat", $"item2").otherwise("")
)
)).show()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.