[英]Remove Specific Value (Column (Number)) from Column(Name) in Scala Spark Dataframe
[英]Finding Percent that are Different from Selected Value Within Specific Groupings for Each Column (Spark Dataframe)
大家好,所以我遇到了一個有趣且困難的問題。
想象一下這樣的Spark數據幀:
A B C D E
1 q 2 3 4
1 t 5 3 5
1 r 1 2 5
2 r 3 1 3
2 t 8 1 3
2 q 1 2 3
3 t 1 1 2
3 r 2 1 2
3 r 3 1 1
現在我有一個非常復雜的問題。
首先,我想按列A分組。然后,我要找到列B等於r的列C的argmax。 然后,我想再次對不等於R的每個B進行分組。然后,我想將groupby中的所有其他值與先前為每個后續列(D和E)選擇的“最大值”值進行比較,並找到百分比匹配和計數。
因此,輸出將是:
A B TotalCount Percent-D-Match Count-D-Match Percent-E-Match Count-E-Match
1 q 1 0 0 0 0
1 t 1 0 0 1 1
2 q 1 0 0 1 1
2 t 1 1 1 1 1
3 t 1 1 1 0 0
我想這將是一個復雜的udaf,但是我不確定如何解決這個問題。 謝謝。
根據您對問題的理解,可以使用以下邏輯
第一步是為maxR和maxNotR計算兩個臨時dataframe
val maxR = df.filter($"B" === "r").groupBy("A").agg(max("C").as("maxR"))
val maxNotR = df.filter($"B" =!= "r").groupBy("A").agg(max("C").as("maxNotR"))
下一步將是join
與他們原來的dataframe
val joinedDF = df.join(maxR, Seq("A"), "left").join(maxNotR, Seq("A"), "left")
由於您不需要B
列中帶有r
的行,因此可以對其進行filter
並生成TotalCount
列
val dff = joinedDF.filter($"B" =!= "r").groupBy("A", "B", "D", "E", "maxR", "maxNotR").agg(count("B").as("TotalCount"))
最后一步是通過比較各列來計算預期輸出
dff.select($"A",
$"B",
$"TotalCount",
when($"D" === $"maxR" || $"D" === $"maxNotR", 1).otherwise(0).as("Percent-D-Match"),
(when($"D" === $"maxR", 1).otherwise(0)+when($"D" === $"maxNotR", 1).otherwise(0)).as("Count-D-Match"),
when($"E" === $"maxR" || $"E" === $"maxNotR", 1).otherwise(0).as("Percent-E-Match"),
(when($"E" === $"maxR", 1).otherwise(0)+when($"E" === $"maxNotR", 1).otherwise(0)).as("Count-E-Match")
)
這將導致您最終的dataframe
為
+---+---+----------+---------------+-------------+---------------+-------------+
|A |B |TotalCount|Percent-D-Match|Count-D-Match|Percent-E-Match|Count-E-Match|
+---+---+----------+---------------+-------------+---------------+-------------+
|1 |q |1 |0 |0 |0 |0 |
|2 |t |1 |0 |0 |1 |1 |
|3 |t |1 |1 |1 |0 |0 |
|2 |q |1 |0 |0 |1 |1 |
|1 |t |1 |0 |0 |1 |1 |
+---+---+----------+---------------+-------------+---------------+-------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.