查找 pyspark Dataframe 中缺失值的列名称

Nit*_*ish 2 bigdata dataframe apache-spark pyspark

我有一个数据框 -

+---+--------+------+-----+-------+
| id|    name|  city|state|country|
+---+--------+------+-----+-------+
|  1|abhishek|  pune| null|   null|
|  2| devansh|  pune|   mh|  india|
|  3| urvashi|bglore|   ka|   null|
+---+--------+------+-----+-------+
Run Code Online (Sandbox Code Playgroud)

我想要一个新列“审计”,其中包含每行都有空值的列列表,因此审计列中的第一行将有[州,国家/地区],第二行为空,第三行为[国家/地区]

我认为我们可以在这里使用 isNull 函数,但我不确定如何获取列名列表。

Ron*_*ain 6

这可以工作,使用isNull

df.withColumn("audit", F.array(*[F.when(F.col(col).isNull(), F.lit(col)) for col in df.schema.names]))\
.withColumn("audit", F.expr("filter(audit, x -> x is not null)"))\
.show()
Run Code Online (Sandbox Code Playgroud)

输入:

+---+--------+------+-----+-------+
| id|    name|  city|state|country|
+---+--------+------+-----+-------+
|  1|abhishek|  pune| null|   null|
|  2| devansh|  pune|   mh|  india|
|  3| urvashi|bglore|   ka|   null|
+---+--------+------+-----+-------+
Run Code Online (Sandbox Code Playgroud)

输出:

+---+--------+------+-----+-------+----------------+
| id|    name|  city|state|country|           audit|
+---+--------+------+-----+-------+----------------+
|  1|abhishek|  pune| null|   null|[state, country]|
|  2| devansh|  pune|   mh|  india|              []|
|  3| urvashi|bglore|   ka|   null|       [country]|
+---+--------+------+-----+-------+----------------+
Run Code Online (Sandbox Code Playgroud)