![](/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.