pyspark - 如何在pyspark中添加一个指示每行nan值数量的附加列
问题描述
我想计算每列(包含整数值)的 nan 值的数量,并添加指示这些 nan 值的附加列。
我们以一个简单的 df 为例。
解决方案
让我们假设您的数据框是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|
+----+----+----+---------+
推荐阅读
- java - IntelliJ 和 gradle 3.0
- node.js - Pool.query 不是一个函数
- java - IntelliJ 代码检查抑制反序列化 POJO
- angular - 带有 http 的 Angular 自定义验证器不起作用
- python - 如何按降序返回我在 python 中编写的以下快速排序代码的值?
- javascript - 无法在节点 js 中获取 POST 数据
- c - C - 如何将文件夹结构复制到另一个文件夹?
- go - 如何解决 vs code - gopls 命令不可用
- reactjs - 模型不加载threeJS drei
- mapreduce - 在 netsuite suitescript 我可以从 Reduce 和 Map 函数中获取 MR 脚本的结果吗?