簡體   English   中英

如何 output 計數來自 Spark dataframe 的兩個二進制列的所有成對組合的計數,即使它是零計數?

[英]How to output the count of all pairwise combination of two binary columns from a Spark dataframe even when it is zero count?

即使計數為零,如何 output 計算來自 Spark dataframe 的兩個二進制(0/1)列的所有成對組合的計數?

final_sdf.groupBy('actual', 'prediction').count().show()

當前 output 是

當前的

但我想要的 output 包括如下零組。

期望的

好的,這樣做的想法是首先創建丟失的二進制行,將值計數分配給 0,過濾,然后 append 數據集。

假設我們的主數據集名為df ,如下所示:

+------+----------+-----+
|actual|prediction|count|
+------+----------+-----+
|1     |1.0       |944  |
|0     |1.0       |208  |
+------+----------+-----+

首先,讓我們創建一個名為array的列,例如值為abs(actual - 1) ,這樣,我們就得到了缺失的二進制值。 然后,我們將其分解回預測並刪除我們的array列。

val df2 = df1
  .withColumn("array", array(col("actual"), abs(col("actual") - 1)))
  .withColumn("prediction", explode(col("array")))
  .drop("array")
+------+----------+-----+
|actual|prediction|count|
+------+----------+-----+
|1     |1         |944  |
|1     |0         |944  |
|0     |0         |208  |
|0     |1         |208  |
+------+----------+-----+

然后我們進行anti連接( df1df2 )並用 0 覆蓋count數值。

val df3 = df2.join(df1, Seq("actual", "prediction", "count"), "anti")
  .withColumn("count", lit(0))
+------+----------+-----+
|actual|prediction|count|
+------+----------+-----+
|1     |0         |0    |
|0     |0         |0    |
+------+----------+-----+

最后,我們合並這兩個數據框:

df1.union(df3).show(10)
+------+----------+-----+
|actual|prediction|count|
+------+----------+-----+
|     1|       1.0|  944|
|     0|       1.0|  208|
|     1|       0.0|    0|
|     0|       0.0|    0|
+------+----------+-----+

這就是我希望你所需要的!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM