【问题标题】:How to remove records with their count per group below a threshold?如何删除每组计数低于阈值的记录?
【发布时间】:2016-03-15 07:45:18
【问题描述】:

这是数据框:

id | sector     | balance
---------------------------
1  | restaurant | 20000
2  | restaurant | 20000
3  | auto       | 10000
4  | auto       | 10000
5  | auto       | 10000

如何查找每个sector 类型的计数并删除特定LIMIT 以下具有sector 类型计数的记录?

以下内容:

dataFrame.groupBy(columnName).count()

给我一​​个值在该列中出现的次数。

如何在 Spark 和 Scala 中使用 DataFrame API 做到这一点?

【问题讨论】:

    标签: scala apache-spark apache-spark-sql spark-dataframe


    【解决方案1】:

    您可以使用 SQL Window 来执行此操作。

    import org.apache.spark.sql.expressions.Window
    yourDf.withColumn("count", count("*")
          .over(Window.partitionBy($"colName")))
          .where($"count">2)
    //    .drop($"count") // if you don't want to keep count column
          .show()
    

    对于您给定的数据框

    import org.apache.spark.sql.expressions.Window
    dataFrame.withColumn("count", count("*")
             .over(Window.partitionBy($"sector")))
             .where($"count">2)
             .show()
    

    您应该会看到如下结果:

    id | sector     | balance | count
    ------------------------------
    3  | auto       | 10000   | 3
    4  | auto       | 10000   | 3
    5  | auto       | 10000   | 3
    

    【讨论】:

      【解决方案2】:

      不知道这是否是最好的方法。但这对我有用。

      def getRecordsWithColumnFrequnecyLessThanLimit(dataFrame: DataFrame, columnName: String, limit: Integer): DataFrame = {
          val g = dataFrame.groupBy(columnName)
                           .count()
                           .filter("count<" + limit)
                           .select(columnName)
                           .rdd
                           .map(r => r(0)).collect()
          dataFrame.filter(dataFrame(columnName) isin  (g:_*))
      }
      

      【讨论】:

        【解决方案3】:

        由于它是一个数据框,因此您可以使用 SQL 查询,例如

        select sector, count(1)
        from TABLE
        group by sector
        having count(1) >= LIMIT
        

        【讨论】:

          猜你喜欢
          • 2022-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-16
          • 1970-01-01
          • 1970-01-01
          • 2021-12-14
          • 2023-04-04
          相关资源
          最近更新 更多