[英]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.