【问题标题】:Pyspark question making count result into a dataframePyspark 问题将计数结果放入数据框中
【发布时间】:2021-12-20 16:18:41
【问题描述】:

我有一个看起来像这样的 pyspark 函数。 \

spark.sql("select count(*) from student_table where student_id is NULL") \
spark.sql("select count(*) from student_table where student_scores is NULL") \
spark.sql("select count(*) from student_table where student_health is NULL")

我得到的结果看起来像 \

+-------+|count(1)|\n-------+|    0|+-------+\n|count(1)|\n-------+|    100|+-------+\n|count(1)|\n-------+|  24145|

我想要做的是使用 pandas 或 pyspark 函数将结果变成每列的数据框。 结果应该具有每列的每个空值结果。
例如,

如果有人可以帮助我,请提前感谢。

【问题讨论】:

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


    【解决方案1】:

    您可以在 3 个查询之间使用联合,但实际上您可以使用一个查询获取每一列的所有空计数:

    spark.sql("""
        SELECT  SUM(INT(student_id IS NULL))     AS student_id_nb_null,
                SUM(INT(student_scores IS NULL)) AS student_scores_nb_null,
                SUM(INT(student_health IS NULL)) AS student_health_nb_null,
        FROM    student_table 
    """).show()
    
    #+------------------+----------------------+----------------------+
    #|student_id_nb_null|student_scores_nb_null|student_health_nb_null|
    #+------------------+----------------------+----------------------+
    #|                 0|                   100|                 24145|
    #+------------------+----------------------+----------------------+
    

    或者通过使用 DataFrame API:

    import pyspark.sql.functions as F    
    
    df.agg(
        F.sum(F.col("student_id").isNull().cast("int")).alias("student_id_nb_null"),
        F.sum(F.col("student_scores").isNull().cast("int")).alias("student_scores_nb_null"),
        F.sum(F.col("student_health").isNull().cast("int")).alias("student_health_nb_null")
    )
    

    【讨论】:

      【解决方案2】:

      使用union all 并将所有查询添加到一个spark.sql

      Example:

      spark.sql("""select "student_id" `column_name`,count(*) `null_result` from tmp where student_id is null \
      union all \
      select "student_scores" `column_name`,count(*) `null_result` from tmp where student_scores is null \
      union all \
      select "student_health" `column_name`,count(*) `null_result` from tmp where student_health is null""").\
      show()
      

      【讨论】:

        猜你喜欢
        • 2017-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-25
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        相关资源
        最近更新 更多