我有一个用例,要在其中使用来自另一个数据集的值。例如:
表1:项目
Name | Price
------------
Apple |10
Mango| 20
Grape |30表2: Item_Quantity
Name | Quantity
Apple |5
Mango| 2
Grape |2我想计算总成本并准备一个最终的数据集。
Cost
Name | Cost
Apple |50 (10*5)
Mango| 40 (20*2)
Grape |60 (30*2)我如何才能在火花中实现这一点?感谢你的帮助。
===================
另一个用例:
这个也需要帮助..。
表1:项目
Name | Code | Quantity
-------------------
Apple-1 |APP | 10
Mango-1| MAN | 20
Grape-1|GRA | 30
Apple-2 |APP | 20
Mango-2| MAN | 30
Grape -2|GRA | 50
Table 2 : Item_CODE_Price
Code | Price
----------------
APP |5
MAN| 2
GRA |2
I want to calculate total cost using code to get the price and prepare a final dataset.
Cost
Name | Cost
--------------
Apple-1 |50 (10*5)
Mango-1| 40 (20*2)
Grape-1 |60 (30*2)
Apple-2 |100 (20*5)
Mango-2| 60 (30*2)
Grape-2 |100 (50*2)发布于 2018-03-09 06:52:19
可以使用相同的join使用相同的Name创建两个表,并使用withColumn创建一个新的column,如下所示
val df1 = spark.sparkContext.parallelize(Seq(
("Apple",10),
("Mango",20),
("Grape",30)
)).toDF("Name","Price" )
val df2 = spark.sparkContext.parallelize(Seq(
("Apple",5),
("Mango",2),
("Grape",2)
)).toDF("Name","Quantity" )
//join and create new column
val newDF = df1.join(df2, Seq("Name"))
.withColumn("Cost", $"Price" * $"Quantity")
newDF.show(false)输出:
+-----+-----+--------+----+
|Name |Price|Quantity|Cost|
+-----+-----+--------+----+
|Grape|30 |2 |60 |
|Mango|20 |2 |40 |
|Apple|10 |5 |50 |
+-----+-----+--------+----+第二种情况是,您只需加入代码,并删除您不希望在最后作为
val newDF = df2.join(df1, Seq("CODE"))
.withColumn("Cost", $"Price" * $"Quantity")
.drop("Code", "Price", "Quantity")这个例子在scala中,如果您需要在java中使用,就不会有太大的差别。
希望这能有所帮助!
https://stackoverflow.com/questions/49188040
复制相似问题