首页 > 解决方案 > 如何检查 Pyspark 中的计数值?

问题描述

我正在尝试创建一个查询,该查询将允许我获取一个表,其中 id 将出现至少 3 个计数,并且这些 id 在 k 列中的值为 0、3、4。

+---+---+
|  i|  k|
+---+---+
| 1 |  0|
| 1 |  3|
| 1 |  4|
| 2 |  0|
| 2 |  3|
| 2 |  3|
+---+---+

我想要的输出是:

+---+---+
|  i|  k|
+---+---+
| 1 |  0|
+---+---+
| 1 |  3|
+---+---+
| 1 |  4|
+---+---+  

这是目前我的代码。但它只显示了一个 id 出现 3 次的表,我不确定如何检查这些计数中至少有 1 个是 0、3 还是 4

    sample= sample.join(
        sample.groupBy('i').count().where(('count == 3')).drop('count'), on=['i']
    )

标签: pythonpyspark

解决方案


您可以k = 0, 3, 4在 groupby 计数之前执行 select distinct on。

df = df.join(
    df.select("i", "k").where("k in (0, 3, 4)").distinct()
      .groupby("i").count().where("count == 3").drop("count"), on=["i"]
)

结果


推荐阅读