【问题标题】:how to count the elements in a Pyspark dataframe如何计算 Pyspark 数据框中的元素
【发布时间】:2020-01-07 06:23:47
【问题描述】:

我有一个 pyspark 数据框。它是一个电影数据集。一列是由| 划分的类型。每部电影都有多种类型。

genres = spark.sql("SELECT DISTINCT genres FROM movies ORDER BY genres ASC")
genres.show(5)

我想统计每个流派有多少部电影。我也想展示那些电影是什么。就像下面这样: 我该怎么做?

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql pyspark-dataframes


    【解决方案1】:

    这是一种方法:

    # sample data
    d = [('Action',), ('Action|Adventure',), ('Action|Adventure|Drama',)]
    df = spark.createDataFrame(d, ['genres',])
    
    # create count
    agg_df = (df
              .rdd
              .map(lambda x: x.genres.split('|')) # gives nested list
              .flatMap(lambda x: x) # flatten the list
              .map(lambda x: (x,)) # convert to tuples
              .toDF(['genres'])
              .groupby('genres')
              .count())
    
    agg_df.show()
    
    +---------+-----+
    |   genres|count|
    +---------+-----+
    |Adventure|    2|
    |    Drama|    1|
    |   Action|    3|
    +---------+-----+
    

    【讨论】:

    • 那么是不是可以不转成rdd直接在dataframe上工作呢?
    • 是的,可以使用 udf 函数,但原生 spark 函数具有速度优势。
    • 使用 DataFrame API 并不意味着使用 UDF,有很多 Spark 内置函数可以做到这一点。我添加了一个答案来展示一种简单的方法。
    【解决方案2】:

    这是一种仅使用 DataFrame API 的方法。首先,使用split函数拆分genres字符串然后explode结果数组和groupBygenres计数:

    data = [["Action"], ["Action|Adventure|Thriller"], ["Action|Adventure|Drama"]]
    df = spark.createDataFrame(data, ["genres"])
    
    df = df.withColumn("genres", explode(split(col("genres"), "[|]"))) \
        .groupBy("genres").count()
    
    df.show()
    

    给予:

    +---------+-----+
    |   genres|count|
    +---------+-----+
    | Thriller|    1|
    |Adventure|    2|
    |    Drama|    1|
    |   Action|    3|
    +---------+-----+
    

    【讨论】:

      【解决方案3】:

      用途:

      import pyspark.sql.functions as f
      df.groupby("generes").agg(f.collect_set("Category"),f.count("Category")).show()
      

      这将获得所需的输出。

      【讨论】:

        猜你喜欢
        • 2019-03-04
        • 2021-12-27
        • 1970-01-01
        • 2017-03-24
        • 1970-01-01
        • 2018-01-29
        • 1970-01-01
        • 2020-10-06
        • 2017-07-16
        相关资源
        最近更新 更多