2017-09-04 79 views
0

我在解決以下問題時遇到問題。 基本上我想找到哪個日期的特定項目(item_code)被出售的最大和最小量。在火花數據幀中彙總多個列

輸入數據幀

item_code, sold_date, price, volume 
101,  10-12-2017, 20, 500 
101,  11-12-2017, 20, 400 
201,  10-12-2017, 50, 200 
201,  13-12-2017, 51, 300 

預計輸出

查找maxmin體積出售date.I希望這個解決方案,而無需使用任何lambda操作。

enter image description here

df.groupBy("item_code")agg(min("volume"),max("volume")) 

上面的人會幫助我獲得max和體積min,但我希望他們有各自的日期。

我用udf試過了我最好的級別,但是我無法破解它。任何幫助高度讚賞。

+0

請嘗試發佈文本樣品而不是圖像。謝謝。 – philantrovert

+0

Thanks.Updated my post @philantrovert – BDR

+0

它din幫助我。我想要在哪個sold_date,給定item_code的最大/最小音量。 first()將相同的日期返回給我的所有結果。 – BDR

回答

1

您想要的最終輸出需要複雜的過程。您可以使用以下過程。

鑑於輸入dataframe作爲

+---------+----------+-----+------+ 
|item_code|sold_date |price|volume| 
+---------+----------+-----+------+ 
|101  |10-12-2017|20 |500 | 
|101  |11-12-2017|20 |400 | 
|201  |10-12-2017|50 |200 | 
|201  |13-12-2017|51 |300 | 
+---------+----------+-----+------+ 

您可以使用下面的代碼

import org.apache.spark.sql.functions._ 
val tempDF = df.groupBy("item_code").agg(min("volume").as("min"),max("volume").as("max")) 
tempDF.as("t2").join(df.as("t1"), col("t1.item_code") === col("t2.item_code") && col("t1.volume") === col("t2.min"), "left") 
    .select($"t2.item_code", $"t2.max", concat_ws(",", $"t2.item_code", $"t2.min", $"t1.sold_date").as("min")) 
    .join(df.as("t3"), col("t3.item_code") === col("t2.item_code") && col("t3.volume") === col("t2.max"), "left") 
    .select($"min", concat_ws(",", $"t3.item_code", $"t2.max", $"t3.sold_date").as("max")) 
    .show(false) 

這將會給你dataframe你的願望

+------------------+------------------+ 
|min    |max    | 
+------------------+------------------+ 
|101,400,11-12-2017|101,500,10-12-2017| 
|201,200,10-12-2017|201,300,13-12-2017| 
+------------------+------------------+ 
+0

似乎是相當昂貴的過程.....需要很多的時間甚至對200MB的數據集。 – BDR

+1

連接總是很貴:) –