【问题标题】:How to add an additional column indicating number of nan values per row in pyspark如何在pyspark中添加一个指示每行nan值数量的附加列
【发布时间】:2020-06-05 17:39:49
【问题描述】:

我想计算每列(包含整数值)的 nan 值的数量,并添加指示这些 nan 值的附加列。

我们以一个简单的 df 为例。

【问题讨论】:

    标签: pyspark


    【解决方案1】:

    让我们假设您的数据框是df,并且您想要扫描它的所有现有列。

    from functools import reduce
    from operator import add
    
    columns2scan = df.columns ## change this if you only want part of columns to scan
    df.withColumn('num_nulls', (reduce(add,(F.when(F.col(x).isNull(),1).otherwise(0) for x in columns2scan )))).show()
    

    例子:

    df.show()  
    +----+----+----+
    |col1|col2|col3|
    +----+----+----+
    |null|   y|   y|
    |null|   x|null|
    |   x|null|null|
    |null|null|null|
    +----+----+----+
    

    然后使用上面的代码我们得到:

    +----+----+----+---------+
    |col1|col2|col3|num_nulls|
    +----+----+----+---------+
    |null|   y|   y|        1|
    |null|   x|null|        2|
    |   x|null|null|        2|
    |null|null|null|        3|
    +----+----+----+---------+
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2020-10-05
      • 2018-02-23
      • 1970-01-01
      • 2019-06-07
      • 2018-03-01
      相关资源
      最近更新 更多