![](/img/trans.png)
[英]How to filter and group pandas DataFrame to get count for combination of two columns
[英]How to output the count of all pairwise combination of two binary columns from a Spark dataframe even when it is zero count?
好的,这样做的想法是首先创建丢失的二进制行,将值计数分配给 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
连接( df1
和df2
)并用 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.