【问题标题】:Is there any method to find number of columns having data in pyspark data frame有什么方法可以在 pyspark 数据框中找到包含数据的列数
【发布时间】:2020-01-19 12:51:34
【问题描述】:

我有一个包含 7 列的 pyspark 数据框,我必须添加一个名为“sum”的新列并计算 sum 列中包含数据(非空)的列数。Example a data frame in which yellow highlighted part is required answer

【问题讨论】:

    标签: sql pyspark


    【解决方案1】:

    这个总和可以这样计算:

    df = spark.createDataFrame([
        (1, "a", "xxx", None, "abc", "xyz","fgh"), 
        (2, "b", None, 3, "abc", "xyz","fgh"),
        (3, "c", "a23", None, None, "xyz","fgh")
    ], ("ID","flag", "col1", "col2", "col3", "col4", "col5"))
    
    from pyspark.sql import functions as F
    from pyspark.sql.types import IntegerType
    
    df2 = df.withColumn("sum",sum([(~F.isnull(df[col])).cast(IntegerType()) for col in df.columns]))
    df2.show()
    +---+----+----+----+----+----+----+---+
    | ID|flag|col1|col2|col3|col4|col5|sum|
    +---+----+----+----+----+----+----+---+
    |  1|   a| xxx|null| abc| xyz| fgh|  6|
    |  2|   b|null|   3| abc| xyz| fgh|  6|
    |  3|   c| a23|null|null| xyz| fgh|  5|
    +---+----+----+----+----+----+----+---+
    

    希望这会有所帮助!

    【讨论】:

    • 谢谢,它给了我错误“列不可迭代”。
    • 实际上,就我而言,它是...F.sum(...) 给了我这样的错误,所以我想说请检查您的导入,这应该可以工作
    • 我已经从 pyspark.sql import functions as F from pyspark.sql.types import IntegerType 中像这样导入了,它仍然无法正常工作。
    • 再一次,这一定与导入有关 - 也许您已经导入了上面覆盖某些功能的东西?请删除所有前面的导入,然后重试。您可以在此处找到对此问题的另一种解释:stackoverflow.com/a/53868119/4113409。在这里我无能为力...
    • 非常感谢,删除 sum (del sum) 后就成功了。
    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    相关资源
    最近更新 更多