繁体   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