首页 > 解决方案 > pyspark 中特定列的每个值始终为 NULL 的列类别

问题描述

我有一个非常大的表,我的数据库是 spark。假设它是这样的:

+----------------------------------------------------------------------------+
| col1  | col2 | col3  | col4(event_type) | col5  | col6  |   ...     |col20 |
+----------------------------------------------------------------------------+
|  null | val1 | val2  |       'A'        | val3  | null  |   ...     | null |
|  val4 | null | val5  |       'B'        | val6  | null  |   ...     | null |
|  null | null | val7  |       'C'        | null  | val8  |   ...     | val9 |
|  null | val1 | vall8 |       'A'        | val2  | null  |   ...     | null |
|............................................................................|
+-----------------------------------------------------------------------------


在这张表中,我们有很多列有很多 NULL 值。该表也有一列是type。对于每个类型值,某些列永远为空。例如在上表中,对于 type='A' col1 和 col5 和 col20 为 NULL。

我想为每种类型提取所有不为空的列名。(例如,对于“A”类型,我想获取 col1、col5 和 col20 名称)。

谁能帮我怎么做?

更新:

正如@Mohammad 所说,我尝试了这个 pyspark 代码:

from pyspark.sql import functions as F

df.groupBy("event_type").agg\
(F.first(F.concat_ws(",",*[(F.when(F.col(x).isNotNull(), F.lit(x)))\
                           for x in df.columns if x!='event_type'])).alias("non_null_columns")).show()

它似乎是正确的,但结果显示不正确。结果是这样的:

+--------------------+-----------------------------------------+
|     event_type     |all_not_null_columns_for_each_event      |
+--------------------+-----------------------------------------+
|    event1_name     |                     timestamp,created...|
|    event2_comple...|                     timestamp,created...|
|    event3_name     |                     timestamp,battery...|
|    event5_name     |                     timestamp,battery...|
|    event6_name     |                     timestamp,battery...|
|    event7_comple...|                     timestamp,created...|
+--------------------+-----------------------------------------+

如您所见,结果并未完全显示,相反,我们看到...

标签: sqlpyspark

解决方案


您可以使用 来实现通过列的循环Pyspark DataFrame API,这是不可能的pure SQL.

df.show() #sampledata
#+----+----+----+----------+
#|col1|col2|col3|event_type|
#+----+----+----+----------+
#|null|val1|val2|         A|
#|val4|null|val5|         B|
#|null|null|val7|         C|
#|null|val1|val8|         A|
#+----+----+----+----------+


from pyspark.sql import functions as F

df.groupBy("event_type").agg\
(F.first(F.concat_ws(",",*[(F.when(F.col(x).isNotNull(), F.lit(x)))\
                           for x in df.columns if x!='event_type'])).alias("non_null_columns")).show()


#+----------+----------------+
#|event_type|non_null_columns|
#+----------+----------------+
#|         B|       col1,col3|
#|         C|            col3|
#|         A|       col2,col3|
#+----------+----------------+

推荐阅读